How to receive only letters and spaces in the input?

Asked

Viewed 95 times

-1

def registro(name="", idade=0, local=""):
    while name.isalpha() == False:
            name = input("Digite seu nome: ")
            if name.isalpha():
                name.isalpha() == True
            else:
                print("Por favor digite um nome válido.(Não deve conter espaços)")

In this code I used "isalpha()" for the reason of receiving only letters, however, this does not allow me to put spaces, which code replacement I could do for the Input to receive only letters and spaces?

  • The use of isalpha was not to receive numbers or special characters in the name, I was not aware that isalpha nullified the spaces. As for the True problem I noticed this too and I already tidied up this part of the code, but in this case, how I would make this input receive only letters and spaces?

  • I think it’s become clearer now.

1 answer

2

Like isalpha() returns True only if all characters are letters, and the name can have letters and spaces, then the way is to check the characters one by one. So:

while True:
    name = input("Digite seu nome: ")
    if all(c.isalpha() or c.isspace() for c in name):
        break # sai do while
    else:
        print("Por favor digite um nome válido (somente letras e espaços)")

I use all, returning True if all the characters in the strings meet the condition (which in this case is c.isalpha() or c.isspace(), i.e., "is a letter or a space".

If all characters are in this condition, the break interrupts the loop. Otherwise, the error message is printed and asked to type again.


Just remembering that isalpha is very comprehensive and also considers letters from other alphabets (Japanese, Russian, Arabic, etc.), and isspace also considers line breaks, TAB, among others.

If you want to be more restricted, just create a string containing only the valid characters and use it in the test:

from string import ascii_letters
 
# acrescentei o espaço e algumas letras acentuadas, adicione tudo que precisar aqui 
validos = ascii_letters + ' áéíóú'
while True:
    name = input("Digite seu nome: ")
    if all(c in validos for c in name):
        break # sai do while
    else:
        print("Por favor digite um nome válido (somente letras e espaços)")

In the above example I used the letters ASCII (all letters from "a" to "z", uppercase and lowercase), and added the space and some accented letters. So just add all the characters you need there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.