当前位置:  首页>> 技术小册>> Python合辑3-字符串用法深度总结

str.split(sep=None, maxsplit=-1)

字符串拆分方法包含两个属性:sep 和 maxsplit。当使用其默认值调用此方法时,它会在任何有空格的地方拆分字符串。此方法返回字符串列表:

  1. string = "Apple, Banana, Orange, Blueberry"
  2. print(string.split())

Output:

  1. ['Apple,', 'Banana,', 'Orange,', 'Blueberry']

可以看到字符串没有很好地拆分,因为拆分的字符串包含 ,。可以使用 sep=’,’ 在有 , 的地方进行拆分:

  1. print(string.split(sep=','))

Output:

  1. ['Apple', ' Banana', ' Orange', ' Blueberry']

这比之前的拆分要好,但是可以在一些拆分字符串之前看到空格。可以使用 (sep=’, ‘) 删除它:

  1. # Notice the whitespace after the comma
  2. print(string.split(sep=', '))

Output:

  1. ['Apple', 'Banana', 'Orange', 'Blueberry']

现在字符串被很好地分割了。有时不想分割最大次数,可以使用 maxsplit 属性来指定打算拆分的次数:

  1. print(string.split(sep=', ', maxsplit=1))
  2. print(string.split(sep=', ', maxsplit=2))

Output:

  1. ['Apple', 'Banana, Orange, Blueberry']
  2. ['Apple', 'Banana', 'Orange, Blueberry']

该分类下的相关小册推荐: