python - 为什么 Python "".split() 和 "".split (",") 会产生不同的结果?

标签 python string split

这是当我对一个空字符串应用 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/

相关文章:

string - Matlab:如何从字符串中删除前缀

Java 的 String.split() 删除尾随的空条目

javascript - 无法调用未定义的方法 'split' - 从函数调用

python - MySQLdb : Operand should contain 1 column(s)

python - 使用 Python : how to keep going after timeout? 中的工作池进行异步多处理

Python:如何从 10 个列表中获取前 5 个或后 5 个?

java - Android/Java - 将 DataInputStream 转换为字符串

Python 临时文件 : broken or am I doing it wrong?

c - 将 printf 语句分配给 int 变量

c# - 我怎样才能删除最后一部分?