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

是python str.split()不一致吗?

发布时间:2020-12-20 12:19:47 所属栏目:Python 来源:网络整理
导读:".a string".split('.')['','a string'] "a .string".split('.')['a ','string'] "a string.".split('.')['a string',''] "a ... string".split('.')['a ','',' string'] "a ..string".split('.')['a ','string'] 'this is a test'.split(' ')['this','is','
>>> ".a string".split('.')
['','a string']

>>> "a .string".split('.')
['a ','string']

>>> "a string.".split('.')
['a string','']

>>> "a ... string".split('.')
['a ','',' string']

>>> "a ..string".split('.')
['a ','string']

>>> 'this  is a test'.split(' ')
['this','is','a','test']

>>> 'this  is a test'.split()
['this','test']

当被调用的字符串只有空格作为空格时,为什么split()与split(”)不同?

为什么拆分(‘.’)将“…”拆分为[”,”]? split()不考虑2个分隔符之间的空字……

文档对此很清楚(参见下面的@agf),但我想知道为什么这是选择的行为.

我查看了源代码(here),思路136应该小于:… i< str_len ...

解决方法

str.split docs,具体提到了这个行为:

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

Python试图做你期望的事情.大多数人都不会想太多

'1 2 3 4 '.split()

回来

['1','3','4']

考虑分割使用空格而不是制表符来创建固定宽度列的数据 – 如果数据宽度不同,则每行中将有不同数量的空格.

在一行的末尾经常有一些你看不到的尾随空格,默认也忽略它 – 它给你你在视觉上期望的答案.

对于指定分隔符时使用的算法,请考虑CSV文件中的行:

1,3

表示第1列和第3列中有数据,第2列中没有数据,因此您需要

'1,3'.split(',')

回来

['1','3']

否则你将无法分辨每个字符串来自哪个列.

(编辑:李大同)

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

    推荐文章
      热点阅读