Alex Rivera | Logout

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

Asked 2011-09-13T17:40:52.000
78

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

(It doesn't matter for me whether the function is Cocoa, ObjC, Python, etc.)


Of course, there might be infinite many characters which might be strange. Thus, it is not really a solution to have a blacklist and to add more and more to that list over the time.

I could have a whitelist. However, I don't really know how to define it. [a-zA-Z0-9 .] is a start but I also want to accept unicode chars which can be displayed in a normal way.

Edit
Report

1 Answer

1

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)
answered 2011-09-13T17:43:36.247

Your Answer