I cant seem to figure out why I keep getting this buggy output.
Input file:
ff1
ff2
ff3
ff10
ff11
ff20
ff21
ff23
gb20
gb10
gh23
Output File:
FF01
FF02
FF03
FF010
FF011
FF020
FF021
FF023
GB020
GB010
GH023
Code:
import os
import sys
#directory is the directory we will work from
directory = "C:\\Users\\user\\Desktop"
os.chdir(directory)
renameWhat = ["ff", "gb", "gh"]
oldFile = open("New Text Document.txt")
buffer = oldFile.read()
for item in renameWhat:
for i in range(0, 50):
if i < 10:
buffer = buffer.replace(item + str(i), item.upper() + "0" + str(i))
else:
buffer = buffer.replace(item + str(i), item.upper() + str(i))
outFile = open("test.txt", "w")
outFile.write(buffer)
outFile.close()
oldFile.close()
What needs to happen:
I’m trying to replace ff to uppercase (done), then I need to add zero’s to all numbers that are less than or equal to 9. So I think that if i is less than 10 should be good enough; but it’s not because it’s adding zeroes to everything over 9. I have tried with len(str(i)) to make sure it’s only of length one, but that still does not work; what am I missing?
The reason your original solution doesn’t work is that it isn’t checking that it’s matching a whole line/word/number. So for instance after replacing
ff1withFF01your buffer is now: