在python中,.split(' ')和.split()之间有根本的区别吗?我认为.split()的默认值是空格,所以两者应该是相同的,但我在hackerrank上得到了不同的结果。
发布于 2020-05-26 10:04:17
根据docs (适用于Python3.8,也是我所强调的):
如果未指定
sep或为None,则应用不同的拆分算法:连续空格的运行被视为single分隔符,如果字符串包含前导或尾随空格,则结果的开头或结尾将不包含空字符串。
所以,不,它们不是一回事。例如(请注意,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', '']发布于 2020-05-26 10:03:38
>>> 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.发布于 2020-05-26 10:05:22
str.split(sep=None, maxsplit=-1)的Documentation here。注意:
如果sep未指定或为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()
[]https://stackoverflow.com/questions/62013468
复制相似问题