Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing everything except letters and spaces from string in Python3.3

I have this example string: happy t00 go 129.129 and I want to keep only the spaces and letters. All I have been able to come up with so far that is pretty efficient is:

print(re.sub("\d", "", 'happy t00 go 129.129'.replace('.', '')))

but it is only specific to my example string. How can remove all characters other than letters and spaces?

like image 374
Gronk Avatar asked Feb 04 '14 22:02

Gronk


1 Answers

whitelist = set('abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ')
myStr = "happy t00 go 129.129$%^&*("
answer = ''.join(filter(whitelist.__contains__, myStr))

Output:

>>> answer
'happy t go '
like image 166
inspectorG4dget Avatar answered Sep 28 '22 10:09

inspectorG4dget