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()
Solution 1:
Alternately:
s_ = filter(lambda c: c.isalpha(), s)
Solution 2:
Solution 3:
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() )
Solution 4:
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))
Solution 5:
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))
Post a Comment for "Python Lambda, Filtering Out Non Alpha Characters"