How do i keep letters only in a string python?

What is the best way to remove all characters from a string that are not in the alphabet? I mean, remove all spaces, interpunction, brackets, numbers, mathematical operators..

For example:

input: 'as32{ vd"s k!+'
output: 'asvdsk'

asked Dec 11, 2015 at 0:16

0

You could use re, but you don't really need to.

>>> s = 'as32{ vd"s k!+'
>>> ''.join[x for x in s if x.isalpha[]]
'asvdsk'    
>>> filter[str.isalpha, s] # works in python-2.7
'asvdsk'
>>> ''.join[filter[str.isalpha, s]] # works in python3
'asvdsk'

answered Dec 11, 2015 at 0:19

timgebtimgeb

74.5k20 gold badges114 silver badges139 bronze badges

If you want to use regular expression, This should be quicker

import re
s = 'as32{ vd"s k!+'
print re.sub['[^a-zA-Z]+', '', s]

prints 'asvdsk'

answered Dec 11, 2015 at 0:26

nehemnehem

11.5k6 gold badges54 silver badges78 bronze badges

Here is a method that uses ASCII ranges to check whether an character is in the upper/lower case alphabet [and appends it to a string if it is]:

s = 'as32{ vd"s k!+'
sfiltered = ''

for char in s:
    if[[ord[char] >= 97 and ord[char] = 65 and ord[char] = 65 and ord[char] = 97 and ord[char] 

Chủ Đề