.split(" ")与.split()有什么区别吗?

4
在Python中,.split(' ').split()之间是否存在根本性的区别? 我相信.split()的默认值是空格,所以这两个应该是相同的,但是我在hackerrank上得到了不同的结果。

4
如果您对一个方法的行为感到困惑,请记得检查文档 - user2357112
你需要查看字符串分割的API文档。https://www.geeksforgeeks.org/python-string-split/ - Danizavtz
4个回答

11
根据Python 3.8的文档(并且强调一下),如果未指定或为None,则使用不同的分割算法:将连续的空白视为单个分隔符,并且如果字符串具有前导或尾随空格,则结果不会包含起始或结束的空字符串。因此,它们不是相同的东西。例如(请注意,在AB之间有两个空格,在开头和结尾各有一个空格):
>>> s = " A  B "
>>> s.split()
['A', 'B']
>>> s.split(" ")
['', 'A', '', 'B', '']

此外,连续的空白字符表示的是任何空白字符,而不仅仅是空格:
>>> s = " A\t  \t\n\rB "
>>> s.split()
['A', 'B']
>>> s.split(" ")
['', 'A\t', '', '\t\n\rB', '']

3
>>> print ''.split.__doc__
S.split([sep [,maxsplit]]) -> list of strings

Return a list of the words in the string S, using sep as the
delimiter string.  If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed
from the result.

2

查看此处的文档,了解str.split(sep=None, maxsplit=-1)。注意:

如果未指定或为None,则应用不同的拆分算法:连续的空格被视为单个分隔符,并且如果字符串具有前导或尾随空格,则结果将不包含开头或结尾的空字符串。因此,使用None作为分隔符拆分空字符串或仅由空格组成的字符串将返回[]。

>>> a = " hello world "
>>> a.split(" ")
['', 'hello', 'world', '']
>>> a.split()
['hello', 'world']

>>> b = "hello           world"
>>> b.split(" ")
['hello', '', '', '', '', '', '', '', '', '', '', 'world']
>>> b.split()
['hello', 'world']

>>> c = "       "
>>> c.split(" ")
['', '', '', '', '', '', '', '']
>>> c.split()
[]

0
文档中清楚提到的:

如果未指定sep或为None,则将应用不同的拆分算法:连续的空白符被视为单个分隔符,并且如果字符串具有前导或尾随空格,则结果将不包含开头或结尾的空字符串。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接