0

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 doing it like that way:

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. Any ideas ?

PS: comma in the specific example brings Error too.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
Vaggelis Manousakis
  • 292
  • 1
  • 5
  • 15

6 Answers6

3

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']
wpercy
  • 9,636
  • 4
  • 33
  • 45
2

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)
wpercy
  • 9,636
  • 4
  • 33
  • 45
Tim Lee
  • 358
  • 2
  • 8
2

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....

Theo
  • 21
  • 1
0

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.

kerk12
  • 26
  • 4
0

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']
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
-2

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]
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118