Dusan Milosevic
Dusan Milosevic

Reputation: 60

Remove parentheses around integers in a string

I want to replace (number) with just number in an expression like this:

4 + (3) - (7)

It should be:

4 + 3 - 7

If the expression is:

2+(2)-(5-2/5)

it should be like this:

2+2-(5-2/5)

I tried

a = a.replace(r'\(\d\+)', '')

where a is a string, but it did not work. Thanks!

Upvotes: 5

Views: 1173

Answers (1)

timgeb
timgeb

Reputation: 78800

Python has a powerful module for regular expressions, re, featuring a substitution method:

>>> import re
>>> a = '2+(2)-(5-2/5)'
>>> re.sub('\((\d+)\)', r'\1', a)
'2+2-(5-2/5)'

Upvotes: 7

Related Questions