Skip to content Skip to sidebar Skip to footer

Python Search And Replace Not Replacing Properly

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:\\Use

Solution 1:

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)) )

Solution 2:

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

For some definition of "should". In fact, your code is recognizing the ff1 part and changing it to FF-01. The extra 0 was already in the buffer.

If you like, you can bang your forehead here --> <--

Solution 3:

Your

ifx<10:

condition is true for 0-9, and false for 10+. That's why you're getting the wrong behavior on #10. Change it to:

ifx<=10:

You'd be surprised how often this happens, to me at least.

Post a Comment for "Python Search And Replace Not Replacing Properly"