Python search and replace not replacing properly
Question: I have this script that needs to replace a file extension and it is not doing
so properly:

    
    
    import os
    import sys
    
    #directory is the directory we will work from
    directory = "C:\\Users\\joe\\Desktop"
    os.chdir(directory)
    
    whatToLookFor = ["Ca", "Cb", "Cd", "Ce", "Cf", "Cg", "Ch", "Ci", "Cj", "Ck", "Cl", "Cm", "Cn", "Co",
                     "Fa", "Fb", "Fc", "Fd", "Fe", "Ff", "Fg", "Fh", "Fi", "Fk", "Fl", "Fm", "Fn", "Fo", 
                     "Fp", "Ga", "Gb", "Gc", "Gd", "Ge", "Gf", "Gg", "Gh", "Gi", "Gj", "Gk", "Gn", "Ja",
                     "Jb", "Jc", "Jd", "Je", "Jf", "Jg", "Jh", "Jk", "Jl", "Jm", "Fj", "cc", "cb", "cd",
                     "ce", "cf", "cg", "ch", "ci", "cj", "ck", "cl", "cm", "cn", "co", "fa", "fb", "fc",
                     "fd", "fe", "ff", "fg", "fh", "fi", "fk", "fl", "fm", "fn", "fo", "fp", "ga", "gb", 
                     "gc", "gd", "ge", "gf", "gg", "gh", "gi", "gj", "gk", "gn", "ja", "jb", "jc", "jd", 
                     "je", "jf", "jg", "jh", "jk", "jl", "jm", "fj"]
    
    oldFile = open("links.htm", "r")
    newFile = open("python test.htm", "w")
    buffer = oldFile.read()
    
    for item in whatToLookFor:
        for x in range(0, 80):
            if x < 10:
                buffer = buffer.replace(item + str(x), item.upper() + "-0" + str(x))
            else:
                buffer = buffer.replace(item + str(x), item.upper() + "-" + str(x))
    
    newFile.write(buffer)
    
    oldFile.close()
    newFile.close()
    

The file ff10 is being changed to FF-010 when it should not be. It should be
changed to FF-10


Answer: Without knowing what your actual input is, it will be very difficult to help,
however, I did notice one thing. It looks like you are trying to make sure you
have two digit numbers in your buffer (after the item from whatToLookFor).

If that's true, life would probably be easier if you replaced this:

    
    
    if x < 10:
        buffer = buffer.replace(item + str(x), item.upper() + "-0" + str(x))
    else:
        buffer = buffer.replace(item + str(x), item.upper() + "-" + str(x))
    

With:

    
    
    sx = str(x)
    tmp = sx if len(sx) >= 2 else "0" + sx
    buffer = buffer.replace(item + sx, item.upper()+ "-" + tmp)
    

Or, even better:

    
    
    buffer = buffer.replace(item + str(x), "%s-%02d" % (item.upper(), int(x)) )
    

