我有一些字符串,其中包含括号和嵌套括号中的文本,如下所示:
(Order Filled (today))
我想提取文本以给出以下结果:
Order Filled today
做这件事最有效的方法是什么?
如果您的目标只是删除所有括号,那么您可以使用replace函数
string = '(Order Filled (today))'
string.replace('(','').replace(')','')
更新:只删除那些有结尾的括号
我知道你要求most efficient way
,但当你使用replace
函数时,它也会删除non nested parentheses
,所以我有一个只删除嵌套括号的函数:
def markup(message):
msg = message
result = ""
markups = "()"
num = 0
# Check if the parentheses
def has_ending(_str, i, msg):
if _str == "(":
return ")" in msg[i+1:]
elif _str == ")":
return False
else:
return False
for i in range(len(msg)) :
t = msg[i]
s = t
# if the char is '(' or ')'
if t in markups:
if has_ending(t, i, msg) and num%2 == 0 :
s = ""
num += 1
elif t == ")" and num%2 == 1 :
s = ""
num += 1
# else
else :
s = t
result += s
return result
print(markup('Hello )(O) (O)( (O)'))
# prints 'Hello )O O (O'
string = '(Order Filled (today))'
x = ''.join(x for x in string if x not in '()')
我更喜欢这个,因为如果你想删除更多的字符,它会更容易扩展