Strings‎ > ‎

Get safe character string

Convert/filter any string into ascii character string to use as filename.



import string

# string input
mystring = 'a|b$$c-12à3.tèx#t?'

# define safe characters (white list)
safechars = string.ascii_lowercase + string.ascii_uppercase + string.digits + '.-'
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-'

# converted into safe filename
filename = ''.join([c for c in mystring if c in safechars])
'abc-123.txt'


isalpha()


Note, using isalpha() or isalnum will include non-ascii letters (ä, è, 文) when applied to Unicode strings (Python3)

Python 2
''.join([c for c in mystring if c.isalnum() or c in ['.','-']])
'abc-123.txt'

Python 3
''.join([c for c in mystring if c.isalnum() or c in ['.','-']])
'abc-12à3.tèxt'