Create (sane/safe) filename from any (unsafe) string

前端 未结 11 1341
醉酒成梦
醉酒成梦 2020-12-28 12:45

I want to create a sane/safe filename (i.e. somewhat readable, no \"strange\" characters, etc.) from some random Unicode string (mich might contain just anything).

(

11条回答
  •  天命终不由人
    2020-12-28 13:23

    Python:

    for c in r'[]/\;,><&*:%=+@!#^()|?^':
        filename = filename.replace(c,'')
    

    (just an example of characters you will want to remove) The r in front of the string makes sure the string is interpreted in it's raw format, allowing you to remove backslash \ as well

    Edit: regex solution in Python:

    import re
    re.sub(r'[]/\;,><&*:%=+@!#^()|?^', '', filename)
    

提交回复
热议问题