Reputation: 473
I have strings that contain text in parentheses and nested parentheses like this:
(Order Filled (today))
I want to extract the text to give the following result:
Order Filled today
What's the most efficient way of doing this?
Upvotes: 1
Views: 132
Reputation: 846
string = '(Order Filled (today))'
string.replace('(','').replace(')','')
I know you asked for most efficient way
but, when you use replace
function, that will also remove the non nested parentheses
, so I have a function that removes only 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'
Upvotes: 3
Reputation: 21
string = '(Order Filled (today))'
x = ''.join(x for x in string if x not in '()')
i prefer this as it extends more easily if you wish to remove more characters
Upvotes: 2