Skip to content Skip to sidebar Skip to footer

Python String.replace() Not Replacing Characters

Some background information: We have an ancient web-based document database system where I work, almost entirely consisting of MS Office documents with the 'normal' extensions (.do

Solution 1:

That's because filename and foldername get thrown away with each iteration of the loop. The .replace() method returns a string, but you're not saving the result anywhere.

You should use:

filename = line[2]
foldername = line[5]

for letter in bad_characters:
    filename = filename.replace(letter, "_")
    foldername = foldername.replace(letter, "_")

But I would do it using regex. It's cleaner and (likely) faster:

p = re.compile('[/:()<>|?*]|(\\\)')
filename = p.sub('_', line[2])
folder = p.sub('_', line[5])

Solution 2:

You are reassigning to the filename and foldername variables at every iteration of the loop. In effect, only * is being replaced.

Solution 3:

You should look at the python string method translate()http://docs.python.org/library/string.html#string.translate with http://docs.python.org/library/string.html#string.maketrans

Editing this to add an example as per comment suggestion below:
import string
toreplace=''.join(["/", "\\", ":", "(", ")", "<", ">", "|", "?", "*"]) 
underscore=''.join( ['_'] * len(toreplace))
transtable = string.maketrans(toreplace,underscore)
filename = filename.translate(transtable)
foldername = foldername.translate(transtable)

Can simplify by making the toreplace something like '/\:,' etc, i just used what was given above

Solution 4:

You are starting over with the base line instead of saving the replaced result, thus you are getting the equivalent to

filename = line[2].replace('*', '_')
foldername = line[5].replace('*', '_')

Try the following

bad_characters = ["/", "\\", ":", "(", ")", "<", ">", "|", "?", "*"]
filename = line[2]
foldername = line[5]
for letter in bad_characters:
    filename = filename.replace(letter, "_")
    foldername = foldername.replace(letter, "_")

Solution 5:

Should use string.replace(str, fromStr, toStr)

bad_characters = ["/", "\\", ":", "(", ")", "<", ">", "|", "?", "*"]
for letter in bad_characters:
    filename = string.replace(line[2], letter, "_")
    foldername = string.replace(line[5], letter, "_")

Post a Comment for "Python String.replace() Not Replacing Characters"