python字符串操作 [英] python string manipulation
本文介绍了python字符串操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有嵌套括号的字符串 s
:s = "AX(p>q)&E((-p)Ur)"
I have a string s
with nested brackets: s = "AX(p>q)&E((-p)Ur)"
我想删除所有括号对之间的所有字符并存储在一个新字符串中,如下所示:new_string = AX&E
I want to remove all characters between all pairs of brackets and store in a new string like this: new_string = AX&E
我尝试这样做:
p = re.compile("\(.*?\)", re.DOTALL)
new_string = p.sub("", s)
它给出输出:AX&Eur)
有没有办法纠正这个问题,而不是迭代字符串中的每个元素?
Is there any way to correct this, rather than iterating each element in the string?
推荐答案
另一个简单的选择是在每个阶段删除最里面的括号,直到没有更多的括号:
Another simple option is removing the innermost parentheses at every stage, until there are no more parentheses:
p = re.compile("\([^()]*\)")
count = 1
while count:
s, count = p.subn("", s)
这篇关于python字符串操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文