The error happens because the method str.isalpha
checks whether all the characters in the string are composed of letters - "alphabetic", according to the documentation puts.
One option is to validate character by character of the string and involve verification in the function all
. Sort of like this:
def is_alpha_space(string):
return all(char.isalpha() or char.isspace() for char in string)
In this example, a Generator Expression is used to verify that each character of the string str
is true to isalpha
or isspace
. After that, the function is used all
to ensure that this check is true for each character of the string.
So you could do it like this:
def is_alpha_space(str):
return all(char.isalpha() or char.isspace() for char in str)
def nome(msg):
while True:
frase = input(msg)
if not (is_alpha_space(frase) and len(frase) >= 12):
# Se a frase não estiver válida, imprima a mensagem. Como não há
# nada depois desse `print` a ser executado, o `while` continuará
# a repetir este bloco até que o usuário digite um nome válido.
print("\033[0;31mOPS! Valores inválidos ou nome curto demais.\033[m")
else:
# Caso contrário (se o nome estiver válido), retorne-o. O `return`,
# como encerra a função, também interromperá o `while`.
return frase
nome_completo = nome("Digite seu nome completo: ")
print("Seja muito bem-vindo, {0}. ".format(nome_completo))
Note that I ended up simplifying the logic of the function nome
similar to what was done in this another answer. Conversion to string using constructor str
is also not required for function return input
, once it already returns a string.
Another alternative to implement the function is_alpha_space
would be using a regular expression, but in that case I think it would be complicated for no reason, since the above solution is already very elegant. :-)
See reference in Soen.
Change
frase.isalpha()
forall(n.isalpha() for n in frase.split(" "))
.– Augusto Vasques