How to remove parentheses and the text inside them from a string in Python

1 Answer

0 votes
import re

"""
Remove all parentheses and the text inside them.

@param text: The input string
@return:     The cleaned string
"""
def remove_parentheses_with_content(text: str) -> str:
    # Remove parentheses and everything inside them
    cleaned = re.sub(r"\([^)]*\)", " ", text)

    # Collapse multiple spaces into one
    cleaned = re.sub(r"\s+", " ", cleaned)

    # Final trim of leading/trailing spaces
    return cleaned.strip()


text = "(An) API (API) (is a) (connection) connects (between) computer programs"
output = remove_parentheses_with_content(text)

print(output)



"""
run:

API connects computer programs

"""

 



answered Jun 1 by avibootz

Related questions

...