Why do Python “”.split() and “”.split(“,”) produce a different result?

生来就可爱ヽ(ⅴ<●) 提交于 2020-06-26 13:41:08

问题


This is the result when I apply split() against an empty string with default delimiter and with a "," as delimiter in Python.

>>> print "".split(',')
['']
>>> print "".split()
[]

Can somebody please explain why we should expect this behavior?


回答1:


The behavior is as documented (emphasis added):

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.

Empty strings are removed only if you do not specify a separator.

Using help From Python's Interactive Prompt

$ 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)

This provides the information quoted above.



来源:https://stackoverflow.com/questions/29586096/why-do-python-split-and-split-produce-a-different-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!