在Python中,
.split(' ')
和.split()
之间是否存在根本性的区别?
我相信.split()
的默认值是空格,所以这两个应该是相同的,但是我在hackerrank上得到了不同的结果。None
,则使用不同的分割算法:将连续的空白视为单个分隔符,并且如果字符串具有前导或尾随空格,则结果不会包含起始或结束的空字符串。因此,它们不是相同的东西。例如(请注意,在A
和B
之间有两个空格,在开头和结尾各有一个空格):>>> 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', '']
>>> 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.
查看此处的文档,了解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()
[]
如果未指定
sep
或为None
,则将应用不同的拆分算法:连续的空白符被视为单个分隔符,并且如果字符串具有前导或尾随空格,则结果将不包含开头或结尾的空字符串。