问题
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