加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python拆分空字符串

发布时间:2020-12-20 11:41:25 所属栏目:Python 来源:网络整理
导读:参见英文答案 When splitting an empty string in Python,why does split() return an empty list while split(‘n’) returns [”]?????????????????????????????????????6个 有人可以在python 2.7.8上解释这个行为: Python 2.7.8 (default,Nov 12 2014,0
参见英文答案 > When splitting an empty string in Python,why does split() return an empty list while split(‘n’) returns [”]?????????????????????????????????????6个
有人可以在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')
['']

由任何空格分割得到一个空列表,但是用新行分割会给出一个带有空字符串的列表.为什么?

谢谢

解决方法

基于 python wiki:

str.split([sep[,maxsplit]])

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 [''].

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读