I have a list like this,
JavaScript
x
2
1
['Therefore', 'allowance' ,'(#)', 't(o)o', 'perfectly', 'gentleman', '(##)' ,'su(p)posing', 'man', 'his', 'now']
2
Expected output:
JavaScript
1
2
1
['Therefore', 'allowance' ,'(#)', 'too', 'perfectly', 'gentleman', '(##)' ,'supposing', 'man', 'his', 'now']
2
Removing the brackets is easy by using .replace()
, but I don’t want to remove the brackets from strings (#) and (##).
my code:
JavaScript
1
11
11
1
ch = "()"
2
3
for w in li:
4
if w in ["(#)", "(##)"]:
5
print(w)
6
7
else:
8
for c in ch:
9
w.replace(c, "")
10
print(w)
11
but this doesn’t remove the brackets from the words.
Advertisement
Answer
You can use re.sub
. In particular, note that it can take a function as repl
parameter. The function takes a match object, and returns the desired replacement based on the information the match object has (e.g., m.group(1)
).
JavaScript
1
10
10
1
import re
2
3
lst = ['Therefore', 'allowance', '(#)', 't(o)o', 'perfectly', 'gentleman', '(##)', 'su(p)posing', 'man', 'his', 'now']
4
5
def remove_paren(m):
6
return m.group(0) if m.group(1) in ('#', '##') else m.group(1)
7
8
output = [re.sub(r"((.*?))", remove_paren, word) for word in lst]
9
print(output) # ['Therefore', 'allowance', '(#)', 'too', 'perfectly', 'gentleman', '(##)', 'supposing', 'man', 'his', 'now']
10