Python string.replace() not replacing characters

后端 未结 5 1122
粉色の甜心
粉色の甜心 2020-12-06 05:43

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\" extens

相关标签:
5条回答
  • 2020-12-06 06:16

    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])
    
    0 讨论(0)
  • 2020-12-06 06:20

    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, "_")
    
    0 讨论(0)
  • 2020-12-06 06:21

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

    0 讨论(0)
  • 2020-12-06 06:27

    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, "_")
    
    0 讨论(0)
  • 2020-12-06 06:32

    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

    0 讨论(0)
提交回复
热议问题