I want to replace a line in a file but my code doesn't do what I want. The code doesn't change that line. It seems that the problem is the space between ALS and 4277 characters in the input.txt. I need to keep that space in the file. How can I fix my code?
A part part of input.txt:
for lines in fileinput.input('input.txt', inplace=True):
print(lines.rstrip().replace("ALS"+str(4277), "KLM" + str(4945)))
As the spaces vary you will need to use regex to account for the spaces.
import re lines = "ALS 4277 " line = re.sub(r"(ALS\s+4277)", "KLM 4945", lines.rstrip()) print(line)