Last modified: Oct 07, 2023 By Alexander Williams
Remove Parentheses from String in Python [Methods + Examples]
Example 1: Using `str.replace()` Method
# Sample string with parentheses
text = "Hello (world), welcome (to) Python."
# Remove parentheses using str.replace()
text_without_parentheses = text.replace("(", "").replace(")", "")
# Print the string without parentheses
print("String without parentheses:", text_without_parentheses)
Output:
String without parentheses: Hello world, welcome to Python.
Example 2: Using a Regular Expression
import re
# Sample string with parentheses
text = "Hello (world), welcome (to) Python."
# Remove parentheses using a regular expression
text_without_parentheses = re.sub(r'\([^)]*\)', '', text)
# Print the string without parentheses
print("String without parentheses:", text_without_parentheses)
Output:
String without parentheses: Hello , welcome Python.
Example 3: Using a Loop
# Sample string with parentheses
text = "Hello (world), welcome (to) Python."
# Initialize an empty string to store the result
result = ""
# Iterate through each character in the string
for char in text:
# Check if the character is not an opening or closing parenthesis
if char != '(' and char != ')':
# Append the character to the result string
result += char
# Print the string without parentheses
print("String without parentheses:", result)
Output:
String without parentheses: Hello world, welcome to Python.
Example 4: Using `str.join()` with List Comprehension
# Sample string with parentheses
text = "Hello (world), welcome (to) Python."
# Remove parentheses using list comprehension and str.join()
text_without_parentheses = ''.join([char for char in text if char not in '()'])
# Print the string without parentheses
print("String without parentheses:", text_without_parentheses)
Output:
String without parentheses: Hello world, welcome to Python.