0

How do I remove alphanum and numbers elements in a list? Below code is not removing, what am I doing wrong here? After research in other stackoverflow, they are removing characters but not the elements itself.

ls = ['1a', 'b3', '1.45','apples','oranges','mangoes']
cleaned = [x for x in ls if x is not x.isalnum() or x is not x.isdigit()]
cleaned

result = re.sub(r'[^a-zA-Z]', "", ls)
print(result) #expected string or bytes-like object

output should be:

['apples','oranges','mangoes']
enter code here
sharp
  • 2,140
  • 9
  • 43
  • 80
  • If you just want alphabet characters, why not check `str.isalpha`? `[x for x in ls if x.isalpha()]`? Do you care about punctuation characters? – Patrick Haugh Jul 19 '18 at 17:09

3 Answers3

2

Try this:

ls = ['1a', 'b3', '1.45','apples','oranges','mangoes']

[l for l in ls if l.isalpha()]

Output:

['apples', 'oranges', 'mangoes']
Ashish Acharya
  • 3,349
  • 1
  • 16
  • 25
0

try this:-

ls = ['1a', 'b3', '1.45','apples','oranges','mangoes']
l = []
for i in ls:
    if not bool(re.search(r'\d', i)):
        l.append(i)
print(l)
jits_on_moon
  • 827
  • 6
  • 10
0

I'd do it like this:

newList = []
for x in ls:
    if x.isalpha():
        newList.append(x)

print(newList)

It works for me. It only adds the element to the new list if they don't contain a number.

kCODINGeroo
  • 443
  • 4
  • 13