0
votes

I tried replacing three words in this string by regular expression. But I only get the last replacements not the whole three.

import re
input_txt='The quick brown fox jumps over the lazy dog.'
dic={'The':'THE', 'fox':'FOX', 'dog':'DOG'}
for i,j in dic.items():
   output2=re.sub(i,j,input_txt)
print(output2)

output2 value:

The quick brown fox jumps over the lazy DOG.

2

2 Answers

3
votes

You are writing your replacements to a new string, from the original input_txt each time. Instead, just overwrite input_txt:

input_txt='The quick brown fox jumps over the lazy dog.'
dic={'The':'THE', 'fox':'FOX', 'dog':'DOG'}
for i,j in dic.items():
   input_txt=re.sub(i,j,input_txt)

>>> print(input_txt)
THE quick brown FOX jumps over the lazy DOG.
0
votes

You just need to change the output2 for input_txt, overwriting it instead of creating a new variable.