这是当我对一个空字符串应用 split() 时的结果,该空字符串具有默认分隔符,并且在 Python 中使用“,”作为分隔符。
>>> print "".split(',')
['']
>>> print "".split()
[]
有人可以解释为什么我们应该期待这种行为吗?
最佳答案
行为如记录(强调):
split(...) 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.
仅当您不指定分隔符时,才会删除空字符串。
使用来自 Python 的交互式提示的 help
$ python
Python 2.7.3 (default, Mar 13 2014, 11:03:55)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = ""
>>> s.split()
[]
>>> help(s.split)
这提供了上面引用的信息。
关于python - 为什么 Python "".split() 和 "".split (",") 会产生不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29586096/