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 ?
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']