Removing a particular pattern of a text file in python

Viewed 243

I have an input file named file1 which contains:

Student 0 : Performed well but can do better. [76.50%]

Student 1 : Brilliant performance. [98.50%]

In this particular file I just want to remove the % part so that it produces output like:

Student 0 : Performed well but can do better.

Student 1 : Brilliant performance.

I tried in this manner:

with open('file1', 'r') as infile, open('file2', 'w') as outfile:
    temp = infile.read().replace("[[0-9]+]", "").replace("%","")
    outfile.write(temp)

But this is only removing the %sign and giving output as:

Student 0 : Performed well but can do better. [76.50]

Student 1 : Brilliant performance. [98.50]

1 Answers

You still need regex:

import re
with open('file1', 'r') as infile, open('file2', 'w') as outfile:
    temp = re.sub("\[[\d+\.%]+\]", "", infile.read())
    outfile.write(temp)
Related