You can use the built in func:str.isidentifier()
in combination with filter()
.
This requires no imports such as re
and works by iterating over each character and returning it if its an identifier. Then you just do a ''.join
to convert the array to a string again.
s1 = 'name/with/slashes'
s2 = 'name '
def clean(s):
s = ''.join(filter(str.isidentifier, s))
return s
print f'{clean(s1)}_' #the _ is there so I can see the end of the string
EDIT:
If, like Hans Bouwmeester in the replies, want numeric values to be included as well, you can create a lambda which uses both the isIdentifier and the isdecimal functions to check the characters. Obviously this can be expanded as far as you want to take it. Code:
s1 = 'name/with/slashes'
s2 = 'name i2, i3 '
s3 = 'epng2 0-2g [ q4o 2-=2 t1 l32!@#$%*(vqv[r 0-34 2]] '
def clean(s):
s = ''.join(filter(
lambda c: str.isidentifier(c) or str.isdecimal(c), s))
return s
#the _ is there so I can see the end of the string
print(f'{ clean(s1) }_')
print(f'{ clean(s2) }_')
print(f'{ clean(s3) }_')
Gives :
namewithslashes_
namei2i3_
epng202gq4o22t1l32vqvr0342_
print repr("a string ")
shows the string in quotes - neater than appending_
to it.