在Python中,如何分割字符串并保留分隔符?
这里有个最简单的解释。我现在用的是:
re.split('\W', 'foo/bar spam\neggs')
>>> ['foo', 'bar', 'spam', 'eggs']
我想要的是:
someMethod('\W', 'foo/bar spam\neggs')
>>> ['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']
原因是我想把一个字符串分割成小块,进行一些操作,然后再把它们组合起来。
21 个回答
38
另一个例子:在非字母数字字符上进行分割,并保留分隔符
import re
a = "foo,bar@candy*ice%cream"
re.split('([^a-zA-Z0-9])', a)
输出结果:
['foo', ',', 'bar', '@', 'candy', '*', 'ice', '%', 'cream']
解释 re.split('([^a-zA-Z0-9])', a)
:
() <- keep the separators
[] <- match everything in between
^a-zA-Z0-9 <- except alphabets, upper/lower and numbers.
54
如果你想根据换行符来分割字符串,可以使用 splitlines(True)
。
>>> 'line 1\nline 2\nline without newline'.splitlines(True)
['line 1\n', 'line 2\n', 'line without newline']
(这不是一个通用的解决方案,但我把它放在这里,以防有人不知道这个方法的存在。)
465
re.split
的文档提到:
通过出现的模式来分割字符串。如果在模式中使用了捕获括号,那么模式中所有组的文本也会作为结果列表的一部分返回。
所以你只需要把你的分隔符放在一个捕获组里:
>>> re.split('(\W)', 'foo/bar spam\neggs')
['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']