Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make string a valid file name that can later be viewed as original string

Say I have a string

"this is | test"

and I want to use that string as a file name but it is not valid to have the | character inside a file name. What is the best way to replace all characters that are not valid as a file name with characters that are valid but later on I can read the saved file name by replacing back all the prior replaced invalid characters?

To explain better say the initial string was

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this is | test

then I replaced the string to "this is # test" and saved the file now I can re-read that file name as the original string by just replacing the # with |. What is the best way to achieve this for all invalid strings?

>Solution :

You can use URL quoting as URL-safe characters are generally safe for filenames too:

>>> import urllib.parse
>>> urllib.parse.quote("this is | test", safe=" ")
'this is %7C test'
>>> urllib.parse.unquote("this is %7C test")
'this is | test'

or you can base64 encode/decode your string:

>>> import base64
>>> base64.b64encode("this is | test".encode())
b'dGhpcyBpcyB8IHRlc3Q='
>>> base64.b64decode(b'dGhpcyBpcyB8IHRlc3Q=').decode()
'this is | test'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading