To remove parentheses from string using Python, the easiest way is to use the Python sub() function from the re module.
import re
string_with_parentheses = "(This is )a (string with parentheses)"
string_without_parentheses = re.sub(r"[()]",'',string_with_parentheses)
print(string_without_parentheses)
#Output:
This is a string with parentheses
If your parentheses are on the beginning and end of your string, you can also use the strip() function.
string_with_parentheses = "(This is a string with parentheses)"
string_without_parentheses = string_with_parentheses.strip("()")
print(string_without_parentheses)
#Output:
This is a string with parentheses
When using string variables in Python, we can easily perform string manipulation to change the value of the string variables.
One such manipulation is to remove parentheses from a string variable. Parentheses in the wrong spots can make reading sentences tricky.
We can easily remove parentheses from strings in Python.
The easiest way to get rid of parentheses is with a regular expression search using the Python sub() function from the re module.
We can easily define a regular expression which will search for parentheses characters, and then using the sub() function, we will replace them with an empty string.
Below are some examples of how you can remove parentheses from string variables using Python with the sub() function.
import re
string_with_parentheses = "(This is )a (string with parentheses)"
string_without_parentheses = re.sub(r"[()]",'',string_with_parentheses)
print(string_without_parentheses)
#Output:
This is a string with parentheses
Using strip() to Remove Parentheses from the Beginning and End of Strings in Python
If your parentheses are on the beginning and end of your string, you can also use the strip() function.
The Python strip() function removes specified characters from the beginning and end of a string.
To remove square parentheses from the beginning and end of a string using Python, we pass “()” to the strip() function as shown below.
string_with_parentheses = "(This is a string with parentheses)"
string_without_parentheses = string_with_parentheses.strip("()")
print(string_without_parentheses)
#Output:
This is a string with parentheses
Hopefully this article has been useful for you to learn how to remove parentheses from string using Python.