Change strings based on a condition in a list using list comprehension

Viewed 33

Let's say I have a list like so:

a = ['abc1', '2def', 'g3h']

And I am trying to make it like this using list comprehension:

['abc', 'def', 'gh']

What I've tried:

[''.join([x for y in a for x in y if x.isalpha()])]

Which produces:

# ['abcdefgh']

Is there a neat way of achieving ['abc', 'def', 'gh'] using list comprehension?

3 Answers

Using str.join in a nested comprehension

Ex:

a = ['abc1', '2def', 'g3h']
print(["".join(j for j in i if j.isalpha()) for i in a])
# -> ['abc', 'def', 'gh']

If you can use regex, I would go for this:

import re
a = ['abc1', '2def', 'g3h']
[re.sub("\d+", "", x) for x in a]

Use of map and filter

list(map(lambda x:"".join(filter(lambda y:y.isalpha(), x))  ,a))
Related