[英]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: 您不需要lambda函数:
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: 如果您确实想使用lambda函数,则可以如下编写:
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
: 要将其转换为单个字符串,可以使用
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: 如果您特别想要或需要使用lambda函数,则可以使用
filter
代替生成器:
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.