Python string.replace() not replacing characters

后端 未结 5 1121
粉色の甜心
粉色の甜心 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: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

提交回复
热议问题