Cleb Cleb - 6 months ago 22
Python Question

How to remove parentheses only around single words in a string

Let's say I have a string like this:

s = '((Xyz_lk) some stuff (XYZ_l)) (and even more stuff (XyZ))'


I would like to remove the parentheses only around single words so that I obtain:

'(Xyz_lk some stuff XYZ_l) (and even more stuff XyZ)'


How would I do this in Python? So far I only managed to remove them along with the text by using

re.sub('\(\w+\)', '', s)


which gives

'( some stuff ) (and even more stuff )'


How can I only remove the parentheses and keep the text inside them?

vks vks
Answer
re.sub(r'\((\w+)\)',r'\1',s)

Use \1 or backreferencing.

Comments