how do i loop through all the letters in a string and see if all letters exist in a list

Question:

I have a string and i need to loop through all of its letter including (if there’s any) white spaces, numbers, symbols, etc…

I have to make sure that the string only contains letters, but my loop only goes through the first letter and then it produces an output straight away thus missing any symbols, white spaces in between letters.

i tried using for loop and even while loop but it’s not giving me the correct output

for char in text:
    if char in letter_list:
        print('the word is in the list')
    elif char not in letter_list:
        print('the word is not in the list')
        break

example:

the string word is ca nada. there is a white space between ca and nada- if that’s the case the output will print:
the letter is not in the list

Asked By: eybisea

||

Answers:

Use regex, as per this answer:
https://stackoverflow.com/a/23476662/4400677

Alternatively: have a list of only valid characters – letters in an array, and check if every character matches.
I only recommend the more complex solution is your ‘legal’ characters are only in a non-ascii language.

In your code, remove the break statement. It will terminate the loop on the first letter not in the list.

Answered By: Friedrich

This…

text = "ce nada"
letter_list = "abcdefghijklmnopqrstuvwxyz"

for char in text:
    if char in letter_list:
        print('the letter is in the list')
    else:
        print('the letter is not in the list')
        break

works if this is the expected output:

the letter is in the list
the letter is in the list
the letter is not in the list

Perhaps a more useful version might be?

text = "ce nada"
letter_list = "abcdefghijklmnopqrstuvwxyz"

for char in text:
    if char not in letter_list:
        print(f"'{char}' is not a letter")
        break
else:
    print("All characters are letters")
Answered By: Thickycat

Difficult to know what you want without knowing what is in the letter_list. Is the letter c not in that list? Please provide the contents of this "letter_list" for clarification.

This will loop through all the letters and print the correct line if they are in the list or not. I just removed the break

import string

text = "ca nada"
letter_list = string.ascii_letters


for char in text:
    if char in letter_list:
        print('the letter is in the list')
    elif char not in letter_list:
        print('the letter is not in the list')
Answered By: en_lorithai
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.