isalpha()
is a method for the str
class which returns True
if all the characters inside a string are letters and False
if that's not the case. Example:
>>> MyString = "fwUBCEFèfewf"
>>> MyString.isalpha()
True
>>> MyOtherString = "f13bbG"
>>> MyOtherString.isalpha()
False
In order to separate all the letters and numbers inside the item array you need to rewrite your code like this:
letters = []
numbers = []
item=[1,7,-10,34,2,"a",-8]
for things in item:
if str(things).isalpha():
letters.append(things)
else:
numbers.append(things)
print(letters)
print(numbers)
# output:
# ['a']
# [1, 7, -10, 34, 2, -8]
You will have to do str(things)
inside the conditions because the isalpha()
is only a function you can use on strings and not integers. If you don't add this you will get an error saying AttributeError: 'int' object has no attribute 'isalpha'
.
You could also do this if you use the isinstance()
function to check wether things
is a string or not. You would do it like this:
letters = []
numbers = []
item=[1,7,-10,34,2,"a",-8]
for things in item:
if isinstance(things, str) and things.isalpha():
letters.append(things)
else:
numbers.append(things)
print(letters)
print(numbers)
# output:
# ['a']
# [1, 7, -10, 34, 2, -8]
Since the letters can only be strings you can check if the things
is of type str
with the isinstance()
function. Here two conditions have to be True
.
I hope that I could help you :)