Reputation: 1
i am running a program that takes a list of numbers and letters, and separates the numbers into a sperate list and printing that list, but every time i run the code it says that isalpha is not defined.
yes = []
item=[1,7,-10,34,2,"a",-8]
for things in item:
if isalpha() ==True:
continue
else:
yes.append
print(yes)
Upvotes: -3
Views: 1078
Reputation: 66
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 :)
Upvotes: 1
Reputation: 4720
.isalpha
is a method not a function (see this tutorial to learn more about the difference), so it cannot be called by name. I think you want
if str(things).isalpha(): continue
or
if isinstance(things, str) and things.isalpha():
continue
Also, the else
is not necessary after continue
, so you can follow with yes.append(things)
(not just yes.append
):
yes = []
item=[1,7,-10,34,2,"a",-8]
for things in item:
if isinstance(things, str) and things.isalpha():
continue
yes.append(things)
print(yes)
(But why are you printing yes
[potentially on repeat] inside the loop instead of after the loop?)
Alternately you could just use list comprehension (view output)
item=[1,7,-10,34,2,"a",-8]
yes = [i for i in item if not (isinstance(i, str) and i.isalpha())]
print(*yes, sep='\n')
Upvotes: 0