How to remove brackets from text file in Python ?
Sometimes it becomes tough to remove brackets from the text file which is unnecessary to us. Hence, python can do this for us. In python, we can remove brackets with the help of regular expressions.
# import re module for using regular expression
patn = re.sub(pattern, repl, sentence)
# pattern is the special RE expression for finding the brackets.
# repl is a string which replaces with the selected things by pattern
# RE is searched in sentence string
The regex pattern used for performing our task:
Note: Here, we have used 2 syntactic characters of regex for doing this-
- […] is a character class that is used to match any one of the characters presents between them
- \ is used for matching the special characters for this, we have brackets as a special character
Here is how it works:
Example 1: Program for removing the brackets with regular expressions from the string
Welcome to geeks for geeks GFG A computer science portal
Now seems like our script is working well. Let’s try the same in a text file. Python enables us to handle files.
Note: For more information, refer File handling in Python.
Example 2: Program for removing brackets from the text file
Example 2: Appending the changes to a new text file