Write a loop that will iterate over a list of items and only output items which have letters inside of a string
Question:
So this is my code in python:
names = ['John', ' ', 'Amanda', 5]
valid = []
for correct_names in names:
if correct_names.isalpha():
valid.append(correct_names)
print(valid)
but when I initialize it I am getting:
AttributeError: ‘int’ object has no attribute ‘isalpha’ I am planning to have an output of
['John', 'Amanda']
without using regular expressions as I am working my way up in learning python again.
Any suggestion is greatly appreciated. Thank you.
Answers:
The requirement is for two restrictions: 1) its a string, 2) it has letters. Use isinstance
for the first and search the string for an alpha for the second.
names = ['John', ' ', 'Amanda', 5]
valid = []
for correct_names in names:
if isinstance(correct_names, str):
for c in correct_names:
if c.isalpha():
valid.append(correct_names)
break
print(valid)
@tdelaney for Foo 2 it will not be considered because isalpha()
So this is my code in python:
names = ['John', ' ', 'Amanda', 5]
valid = []
for correct_names in names:
if correct_names.isalpha():
valid.append(correct_names)
print(valid)
but when I initialize it I am getting:
AttributeError: ‘int’ object has no attribute ‘isalpha’ I am planning to have an output of
['John', 'Amanda']
without using regular expressions as I am working my way up in learning python again.
Any suggestion is greatly appreciated. Thank you.
The requirement is for two restrictions: 1) its a string, 2) it has letters. Use isinstance
for the first and search the string for an alpha for the second.
names = ['John', ' ', 'Amanda', 5]
valid = []
for correct_names in names:
if isinstance(correct_names, str):
for c in correct_names:
if c.isalpha():
valid.append(correct_names)
break
print(valid)
@tdelaney for Foo 2 it will not be considered because isalpha()