Python:如何在字符串拆分中包含定界符? [英] Python: How can I include the delimiter(s) in a string split?
问题描述
我想用多个定界符分割一个字符串,但是将定界符保留在结果列表中.我认为这是第一步,解析任何一种公式都是很有用的,我怀疑有一个不错的Python解决方案.
I would like to split a string, with multiple delimiters, but keep the delimiters in the resulting list. I think this is a useful thing to do an an initial step of parsing any kind of formula, and I suspect there is a nice Python solution.
Someone asked a similar question in Java here.
例如,典型的拆分如下所示:
For example, a typical split looks like this:
>>> s='(twoplusthree)plusfour'
>>> s.split(f, 'plus')
['(two', 'three)', 'four']
但是我正在寻找一种添加加号(或保留它)的好方法:
But I'm looking for a nice way to add the plus back in (or retain it):
['(two', 'plus', 'three)', 'plus', 'four']
最终,我想对每个运算符和括号进行此操作,因此,如果有一种获取方法
Ultimately I'd like to do this for each operator and bracket, so if there's a way to get
['(', 'two', 'plus', 'three', ')', 'plus', 'four']
一劳永逸,然后一切都会好起来.
all in one go, then all the better.
推荐答案
您可以使用Python的re
模块来做到这一点.
You can do that with Python's re
module.
import re
s='(twoplusthree)plusfour'
list(filter(None, re.split(r"(plus|[()])", s)))
如果只需要迭代器,则可以省略列表.
You can leave out the list if you only need an iterator.
这篇关于Python:如何在字符串拆分中包含定界符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!