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

前端 未结 11 1207
醉酒成梦
醉酒成梦 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:44

    Python:

    "".join([c for c in filename if c.isalpha() or c.isdigit() or c==' ']).rstrip()
    

    this accepts Unicode characters but removes line breaks, etc.

    example:

    filename = u"ad\nbla'{-+\)(ç?"
    

    gives: adblaç

    edit str.isalnum() does alphanumeric on one step. – comment from queueoverflow below. danodonovan hinted on keeping a dot included.

        keepcharacters = (' ','.','_')
        "".join(c for c in filename if c.isalnum() or c in keepcharacters).rstrip()
    

提交回复
热议问题