Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove parentheses only around single words in a string

Tags:

python

regex

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?

like image 728
Cleb Avatar asked Jul 14 '15 11:07

Cleb


Video Answer


1 Answers

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

Use \1 or backreferencing.

like image 64
vks Avatar answered Oct 05 '22 22:10

vks