开发者

python lambda, filtering out non alpha characters

i'm trying to keep only the letters in a str开发者_运维知识库ing. i am trying to do something like this:

s = '1208uds9f8sdf978qh39h9i#H(&#*H(&H97dgh'
s_ = lambda: letter if letter.isalpha(), s

this errors out. how would a working version look?


Alternately:

s_ = filter(lambda c: c.isalpha(), s)


how about

re.sub('[^a-zA-Z]','', s)

or

"".join([x for x in s if x.isalpha()])


One handy way to manipulate strings is using a generator function and the join method:

result = "".join( letter for letter in s if letter.isalpha() )


You don't need a lambda function:

result = ''.join(c for c in input_str if c.isalpha())

If you really want to use a lambda function you could write it as follows:

result = ''.join(filter(lambda c:str.isalpha(c), input_str))

But this can also be simplified to:

result = ''.join(filter(str.isalpha, input_str))


You probably want a list comprehension here:

s_ = [letter for letter in s if letter.isalpha()]

However, this will give you a list of strings (each one character long). To convert this into a single string, you can use join:

s2 = ''.join(s_)

If you want, you can combine the two into a single statement:

s_ = ''.join(letter for letter in s if letter.isalpha())

If you particularly want or need to use a lambda function, you can use filter instead of the generator:

my_func = lambda letter: letter.isalpha()
s_ = ''.join(filter(my_func, s))


>>> s = '1208uds9f8sdf978qh39h9i#H(&#*H(&H97dgh'
>>> ''.join(e for e in s if e.isalpha())
'udsfsdfqhhiHHHdgh'


This is kind of the long way round, but will let you create a filter for any arbitrary set of characters.

import string

def strfilter(validChars):
    vc = set(validChars)
    def filter(s):
        return ''.join(ch for ch in s if ch in vc)
    return filter

filterAlpha = strfilter(string.letters)
filterAlpha('1208uds9f8sdf978qh39h9i#H(&#*H(&H97dgh')  # -> 'udsfsdfqhhiHHHdgh'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜