Python 的 split 函数默认是用换行符还是空格来分割

Does Python's split function splits by a newline or a whitespace by default

我正在学习Python。特别是,我读到了 python 字符串的拆分方法和 came to know split 的默认分隔符是一个空格。所以我了解以下工作原理:

text = 'Hello World'
print(text.split())   #this should print ['Hello', 'World'] which it does

上述程序在 Python3.6 中的输出是预期的 ['Hello', 'World'],因为在上述字符串变量 text 中我们有空格。

但后来我尝试了以下示例:

text = 'Hello\nWorld'
print(text.split())    #this should print ['Hello\nWorld'] but it doesn't 

上面的实际输出是:

['Hello', 'World']  #this shouldn't happen because there is no whitespace in text

虽然上面的预期输出是:

['Hello\nWorld']    #this should happen because there is no whitespace in text

如您所见,由于 'Hello''World' 之间没有空格,输出应该是 ['Hello\nWorld'] 因为 \n 不是空格,而空格是split 方法的默认分隔符。

这里发生了什么。

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

Tabs (\t), newlines (\n), spaces, etc. 它们都算作 whitespace 字符,因为从技术上讲,它们都用于相同的目的。把space事情搞定。