Vaggelis Manousakis
Vaggelis Manousakis

Reputation: 391

If statement that keeps characters only

Let's say we have a list list_a = [a,b,C,.,/,!,d,E,f,]

I want to append to a new list only the letters of the alphabet.

So the new list will be list_b = [a,b,C,d,E,f]. So far I have tried the following:

list_b = []
for elements in list_a:
    try:
        if elements == str(elements):
            list_b.append(elements)
    except ValueError: #Catches the Error when the element is not a letter
        continue

However, when I print the list_b it has all the elements of list_a, it doesn't do the job I expected. Also, a comma in the example above brings an error. Any ideas ?

Upvotes: 0

Views: 581

Answers (6)

Vasilis G.
Vasilis G.

Reputation: 7844

Well, it is basically the same logic of using isalpha() method, but you can do this by using filter:

list_a = ['a','b','C','.','/','!','d','E','f']

list_b = list(filter(lambda i: i.isalpha(), list_a))

print(list_b)

Output:

['a', 'b', 'C', 'd', 'E', 'f']

Upvotes: 0

kerk12
kerk12

Reputation: 1

You can try this:

import string
for item in list_a:
    if item in string.ascii_letters:
        list_b.append(item)

Also, check out the string module. It has a lot of additional methods that can help you, should you wish to work with strings. Do note that this works only with ascii characters. If you want to check for every character in an alphabet, then you can via the isalpha() method, as the others have noted above.

Upvotes: -1

wpercy
wpercy

Reputation: 10090

You can use the .isalpha() method of the string type.

In [1]: list_a = ['a','b','C','.','/','!','d','E','f']

In [2]: list_b = [i for i in list_a if i.isalpha()]

In [3]: list_b
Out[3]: ['a', 'b', 'C', 'd', 'E', 'f']

Upvotes: 4

Theo
Theo

Reputation: 21

You are missing the fact that the str() function does not return the "str" elements you think it does, just an str representation of them. Try creating a list with you dictionary [a-zA-Z] (not very pythonic but simple to grasp) and check if your character exists in it. I suggest writing your own code from scratch instead of copy/pasting, that is the only way to really understand the problem....

Upvotes: 2

Tim Lee
Tim Lee

Reputation: 358

Try checking if the character is an alphabet by using the .isalpha() function.

list_b = []
for elements in list_a:
   if elements.isalpha():
        list_b.append(elements)

Upvotes: 2

Brendan Abel
Brendan Abel

Reputation: 37549

You can use the string or re package to do this

import re
new_list = [c for c in old_list if re.match(r'[a-zA-Z]', c)]

Or with string

import string
new_list = [c for c in old_list if c in string.ascii_letters]

Upvotes: -2

Related Questions