只有在某个字符后面没有紧跟着另一个特定的ch时,才拆分该字符串

2024-04-18 10:51:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的代码行,它将字符串data2拆分为一个空白实例的列表:

string_list = data2.split()

但是在我的一些数据中,日期的格式是"28, Dec"。在这里,上面的代码在我不希望的日期和月份之间的空白处分裂。有没有办法我可以说“在空白处分开,但如果是在逗号之后就不行了”?在


Tags: 数据实例字符串代码列表string格式空白
3条回答

re.split与负lookbehind表达式一起使用:

re.split(r'(?<!,)\s','I went on 28, Dec')
Out[53]: ['I', 'went', 'on', '28, Dec']

您需要使用regular expressions。在

>>> re.split('(?<!,) ', 'blah blah, blah')
['blah', 'blah, blah']

从链接:

(?<!...) Matches if the current position in the string is not preceded by a match for .... This is called a negative lookbehind assertion. Similar to positive lookbehind assertions, the contained pattern must only match strings of some fixed length. Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched.

可以使用正则表达式拆分,也可以使用look-behind表达式来确保不会在前面有逗号的空白字符上拆分:

>>> import re
>>> s = 'foo bar 28, Dec bar baz'
>>> re.split('(?<!,)\s', s)
['foo', 'bar', '28, Dec', 'bar', 'baz']

相关问题 更多 >