📌  相关文章
📜  在 python 中分隔字符串(1)

📅  最后修改于: 2023-12-03 15:07:46.368000             🧑  作者: Mango

在 Python 中分隔字符串

在 Python 中,分隔字符串是一项非常常见的操作。它可以让我们将一个大字符串分成几个小部分,或者是将一个小字符串按照某个分隔符分成多个部分。

下面我们来介绍几种 Python 中分隔字符串的方法。

1. 使用 split 函数分隔字符串

split 函数可以按照指定的分隔符将字符串分隔成一个列表。

s = "hello, world"
words = s.split(", ")
print(words)  # ['hello', 'world']

在这个例子中,我们将字符串 s 按照 , 进行分隔,得到了一个包含两个元素的列表。

如果不指定分隔符,则默认按照空格进行分隔。

s = "hello world"
words = s.split()
print(words)  # ['hello', 'world']

我们也可以限制分割后的元素个数,使用 maxsplit 参数来指定最大分割次数。

s = "a b c d e"
words = s.split(" ", maxsplit=2)
print(words)  # ['a', 'b', 'c d e']
2. 使用 partition 函数分隔字符串

partition 函数可以在指定的分隔符处将字符串分成三部分:分隔符前面的部分、分隔符本身、以及分隔符后面的部分。

s = "hello, world"
before, sep, after = s.partition(", ")
print(before)  # 'hello'
print(sep)     # ', '
print(after)   # 'world'

如果字符串中没有指定的分隔符,则将整个字符串作为前部分,后面两个部分为空字符串。

s = "hello world"
before, sep, after = s.partition(", ")
print(before)  # 'hello world'
print(sep)     # ''
print(after)   # ''
3. 使用 rsplit 函数分隔字符串

rsplit 函数与 split 函数类似,区别在于它从字符串的右边开始分隔。它也可以指定分隔符和最大分割次数。

s = "a b c d e"
words = s.rsplit(" ", maxsplit=2)
print(words)  # ['a b', 'c', 'd e']
4. 使用 splitlines 函数分隔字符串

splitlines 函数可以将一个多行字符串按照行进行分割,并返回一个包含每行字符串的列表。

s = "hello\nworld"
lines = s.splitlines()
print(lines)  # ['hello', 'world']

我们可以通过指定 keepends=True 参数来保留换行符。

s = "hello\nworld"
lines = s.splitlines(keepends=True)
print(lines)  # ['hello\n', 'world']

以上就是 Python 中分隔字符串的方法,希望对你有所帮助。