python lambda, filtering out non alpha characters

2019-08-14 15:04发布

i'm trying to keep only the letters in a string. 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?

标签: python lambda
7条回答
Ridiculous、
2楼-- · 2019-08-14 15:32

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'
查看更多
萌系小妹纸
3楼-- · 2019-08-14 15:36

how about

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

or

"".join([x for x in s if x.isalpha()])
查看更多
男人必须洒脱
4楼-- · 2019-08-14 15:42

Alternately:

s_ = filter(lambda c: c.isalpha(), s)
查看更多
闹够了就滚
5楼-- · 2019-08-14 15:44

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))
查看更多
叛逆
6楼-- · 2019-08-14 15:49

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))
查看更多
贪生不怕死
7楼-- · 2019-08-14 15:52

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() )
查看更多
登录 后发表回答