python拆分空字符串 [英] python split empty string
问题描述
有人可以在 python 2.7.8 上解释这种行为吗:
Could someone explain this behaviour on python 2.7.8:
Python 2.7.8 (default, Nov 12 2014, 02:03:09)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = ''
>>> a.split()
[]
>>> a.split('\n')
['']
被任何空格分割会得到一个空列表,但被新行分割会得到一个带有空字符串的列表.为什么?
split by any white space gives an empty list, but split by new line gives a list with an empty string. WHY?
谢谢
推荐答案
基于 python 维基 :
str.split([sep[, maxsplit]])
如果给出了 sep,则连续的分隔符不会组合在一起并被视为分隔空字符串(例如,'1,,2'.split(',')
返回 ['1', '', '2']
).sep 参数可能由多个字符组成(例如,'1<>2<>3'.split('<>')
返回 ['1', '2', '3']
).用指定的分隔符拆分空字符串返回 ['']
.
If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',')
returns ['1', '', '2']
). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>')
returns ['1', '2', '3']
). Splitting an empty string with a specified separator returns ['']
.
如果 sep
未指定或为 None
,则应用不同的拆分算法:将连续空白的运行视为单个分隔符,结果将不包含如果字符串有前导或尾随空格,则在开头或结尾处为空字符串.因此,用 None
分隔符分割空字符串或仅由空格组成的字符串将返回 []
.
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. Consequently, splitting an empty string or a string consisting of just whitespace with a None
separator returns []
.
有关更多解释,请阅读此答案https://stackoverflow.com/a/16645307/2867928
For more explanation read this answer too https://stackoverflow.com/a/16645307/2867928
这篇关于python拆分空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!