在Python语言中有没有等价物str.split
也会返回分隔符?
在处理一些标记之后,我需要为输出保留空白布局。
示例:
>>> s="\tthis is an example"
>>> print s.split()
['this', 'is', 'an', 'example']
>>> print what_I_want(s)
['\t', 'this', ' ', 'is', ' ', 'an', ' ', 'example']
谢谢!
发布于 2009-11-30 23:08:12
怎么样
import re
splitter = re.compile(r'(\s+|\S+)')
splitter.findall(s)
发布于 2009-11-30 23:08:57
>>> re.compile(r'(\s+)').split("\tthis is an example")
['', '\t', 'this', ' ', 'is', ' ', 'an', ' ', 'example']
发布于 2009-11-30 23:09:01
re
模块提供以下功能:
>>> import re
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
(引用自Python文档)。
对于您的示例(以空格拆分),请使用re.split('(\s+)', '\tThis is an example')
。
关键是要在捕获括号中包含要拆分的正则表达式。这样,分隔符就会添加到结果列表中。
编辑:如上所述,任何前面/后面的分隔符当然也会添加到列表中。为了避免这种情况,您可以先对输入字符串使用.strip()
方法。
https://stackoverflow.com/questions/1820336
复制相似问题