Search code examples
pythonpython-re

why does re.sub replaces none of the occurrences even there is already pattern, repl and string added


a.txt is a file with this string:

g g abc
abc
457625

er
oldstring = "abc"
newstring = "def"
with open('a.txt', 'r') as f:
       data = f.read()
       re.sub(r"\b{}\b".format(oldstring), r"\b{}\b".format(newstring), data)
with open('b.txt', 'w') as out:
       out.write(data)

With this python code, I thought I can end up having b.txt where I can have "abc" turned to "def". Surprisingly, I get the exact same string I have in a.txt.

Can anyone tell me where is the error in my code?


Solution

  • You need to assign the output of the re.sub back to the original variable.

       data = re.sub(r"\b{}\b".format(oldstring), newstring, data)