Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove contents between brackets from string

Tags:

python

string

I have a string like this:

s = 'word1 word2 (word3 word4) word5 word6 (word7 word8) word9 word10'

how can I delete everything that is in brackets, so that the output is:

'word1 word2 word5 word6 word9 word10'

I tried regular expression but that doesn't seem to work. Any suggestions?

Best Jacques

like image 394
Jacques Knie Avatar asked Jan 19 '23 02:01

Jacques Knie


1 Answers

import re
s = re.sub(r'\(.*?\)', '', s)

Note that this deletes everything between parentheses only. This means you'll be left with double space between "word2 and word5". Output from my terminal:

>>> re.sub(r'\(.*?\)', '', s)
'word1 word2  word5 word6  word9 word10'
>>> # -------^ -----------^ (Note double spaces there)

However, the output you have provided isn't so. To remove the extra-spaces, you can do something like this:

>>> re.sub(r'\(.*?\)\ *', '', s)
'word1 word2 word5 word6 word9 word10'
like image 108
Susam Pal Avatar answered Jan 21 '23 17:01

Susam Pal