Python string.replace() not replacing characters

醉酒当歌 提交于 2019-11-30 11:43:15

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

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

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

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, "_")

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, "_")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!