Open In App

How to remove brackets from text file in Python ?

Improve
Improve
Like Article
Like
Save
Share
Report

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

Syntax:

# import re module for using regular expression

import re

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

Python3




# importing re module for creating
# regex expression
import re
 
# string for passing
text = "Welcome to geeks for geeks [GFG] A (computer science portal)"
 
# creating the regex pattern & use re.sub()
# [\([{})\]] is a RE pattern for selecting
# '{', '}', '[', ']', '(', ')' brackets.
patn = re.sub(r"[\([{})\]]", "", text)
 
print(patn)


Output:

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

File Used: 

Python3




# importing re module for creating
# regex expression
import re
 
# reading line by line
with open('data.txt', 'r') as f:
   
    # looping the para and iterating
    # each line
    text = f.read()
     
    # getting the pattern for [],(),{}
    # brackets and replace them to empty
    # string
    # creating the regex pattern & use re.sub()
    patn = re.sub(r"[\([{})\]]", "", text)
 
print(patn)


 
 

Output:

 

 

Example 2: Appending the changes to a new text file

 

File Used:

 

 

Python3




# importing re module for creating
# regex expression
import re
 
# reading line by line
with open('input.txt', 'r') as f:
   
    # store in text variable
    text = f.read()
     
    # getting the pattern for [],(),{}
    # brackets and replace them to empty string
    # creating the regex pattern & use re.sub()
    pattern = re.sub(r"[\([{})\]]", "", text)
 
 
# Appending the changes in new file
# It will create new file in the directory
# and write the changes in the file.
with open('output.txt', 'w') as my_file:
    my_file.write(pattern)


Output:



Last Updated : 21 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads