简体   繁体   中英

python lambda, filtering out non alpha characters

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?

how about

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

or

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

交替:

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

一种方便的操作字符串的方法是使用生成器函数和join方法:

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM