str.split(sep=None, maxsplit=-1)
字符串拆分方法包含两个属性:sep 和 maxsplit。当使用其默认值调用此方法时,它会在任何有空格的地方拆分字符串。此方法返回字符串列表:
string = "Apple, Banana, Orange, Blueberry"
print(string.split())
Output:
['Apple,', 'Banana,', 'Orange,', 'Blueberry']
可以看到字符串没有很好地拆分,因为拆分的字符串包含 ,。可以使用 sep=’,’ 在有 , 的地方进行拆分:
print(string.split(sep=','))
Output:
['Apple', ' Banana', ' Orange', ' Blueberry']
这比之前的拆分要好,但是可以在一些拆分字符串之前看到空格。可以使用 (sep=’, ‘) 删除它:
# Notice the whitespace after the comma
print(string.split(sep=', '))
Output:
['Apple', 'Banana', 'Orange', 'Blueberry']
现在字符串被很好地分割了。有时不想分割最大次数,可以使用 maxsplit 属性来指定打算拆分的次数:
print(string.split(sep=', ', maxsplit=1))
print(string.split(sep=', ', maxsplit=2))
Output:
['Apple', 'Banana, Orange, Blueberry']
['Apple', 'Banana', 'Orange, Blueberry']