Reputation: 89
I want to write a code that will take out all Non-Alpha character from a string. Alpha Characters are a-z,A-Z,and 0-9. So this code will also remove spaces but not crash on an empty string. For example:
to_alphanum('Cats go meow')
#it would return:
'Catsgomeow'
to_alphanum('')
#it would return:
''
Is there a way to do this?
Upvotes: 1
Views: 120
Reputation: 42017
str
has isalnum
method to check for alphanumerics, leverage that:
In [115]: def to_alphanum(text):
...: return ''.join([char for char in text if char.isalnum()])
...:
In [116]: to_alphanum('Cats go meow')
Out[116]: 'Catsgomeow'
In [117]: to_alphanum('#$')
Out[117]: ''
In [118]: to_alphanum('190 $%6')
Out[118]: '1906'
Upvotes: 1