Skip to content Skip to sidebar Skip to footer

How To Add A Missing Closing Parenthesis To A String In Python?

I have multiple strings to postprocess, where a lot of the acronyms have a missing closing bracket. Assume the string text below, but also assume that this type of missing bracket

Solution 1:

You may use

text = re.sub(r'(\([A-Z]+(?!\))\b)', r"\1)", text)

With this approach, you can also get rid of the check if the text has ) in it before, see a demo on regex101.com.


In full:

import re
 
#original string
text = "The dog walked (ABC in the park"
text = re.sub(r'(\([A-Z]+(?!\))\b)', r"\1)", text)
print(text)

This yields

The dog walked (ABC) in the park

See a working demo on ideone.com.


Solution 2:

For the typical example you have provided, I don't see the need of using regex You can just use some string methods:

text = "The dog walked (ABC in the park"
withoutClosing = [word for word in text.split() if word.startswith('(') and not word.endswith(')') ]
withoutClosing
Out[45]: ['(ABC']

Now you have the words without closing parenthesis, you can just replace them:

for eachWord in withoutClosing:
    text = text.replace(eachWord, eachWord+')')
    
text
Out[46]: 'The dog walked (ABC) in the park'

Post a Comment for "How To Add A Missing Closing Parenthesis To A String In Python?"