Python - How To Remove Parentheses From String in Python

ID : 51

viewed : 169

Tags : PythonPython StringPython Regex

vote vote

94

This tutorial will demonstrate the methods to remove a set of parentheses from a specific string in Python.

Remove Parentheses From a String With String Manipulation in Python

By default, we have many functions available to perform string manipulation in Python. For this specific problem, we can utilize the in Python.

The replace() function replaces a string or character inside our main string with another string or character. This function takes two arguments: the old value and the new value. It replaces the old value with the new value and returns the new string.

The following example code shows us how to remove a set of parentheses from our string with the replace() function.

string = "(This is (a) string)" string = string.replace("(","").replace(")","") print(string) 

Output:

This is a string 

We removed the parentheses inside our string variable using the string.replace() function in the code above. We achieved our goal by replacing the opening and closing parentheses with an empty string and storing the return value inside our original string.

Remove Parentheses From a String With Regular Expressions in Python

We can also achieve the same output as our previous example by using regular expressions in Python. To use regular expressions, we first have to import the re module into our code. The can be used here.

This function takes the pattern, the replacement, and the original string; it replaces the pattern with the replacement inside the original string and returns the output.

The following example program shows us how to use the re.sub() function to remove parentheses from a string.

import re string = "(This is (a) string)" string = re.sub("[()]","", string) print(string) 

Output:

This is a string 

We removed parentheses from our string variable using the re.sub() function in the code above. We achieved our goal by replacing the opening and closing parentheses with an empty string and storing the return value inside our original string.

Although this approach is a little complex and requires some understanding of the basic concept of regular expressions in Python, this approach is the most recommended one. Regular expressions have a wide range of applications compared to the simple replace() function for string. Every good Python programmer must at least have a basic understanding of regular expressions.

  • Related HOW TO?