Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 934
Dusan Milosevic Avatar asked Dec 12 '15 22:12

Dusan Milosevic


People also ask

How do I remove parentheses from a string?

For this, the most straightforward method is by using the replace() function to replace every occurrence of the parentheses with an empty string. We also discussed the use of regex to achieve this. For using regex to remove parentheses from string in Python, we can use the re. sub() or pandas.

How do you replace parentheses in a string?

Use the PowerShell String replace() method or replace operator to replace the parentheses in a string with an empty space. e.g. $str. replace('(','') replace the parentheses with a blank. The replace() method returns a string where all parentheses are replaced by an empty space.

How do you remove Round brackets from a string in Python?

In python, we can remove brackets with the help of regular expressions. # pattern is the special RE expression for finding the brackets.

How do I get rid of text between parentheses in Python?

Method 1: We will use sub() method of re library (regular expressions). sub(): The functionality of sub() method is that it will find the specific pattern and replace it with some string. This method will find the substring which is present in the brackets or parenthesis and replace it with empty brackets.


1 Answers

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)'
like image 155
timgeb Avatar answered Sep 30 '22 04:09

timgeb