Check that the string only contains Python letter and space

Asked

Viewed 302 times

2

I want the user to enter their full name, but if they put something other than letters, it should display an alert message.

The problem is that the user’s full name requires space between words, and my program is considering these spaces as a different letter character.

How do I solve this problem and make my program accept letters and spaces?

Code below:

def nome(msg):
    valido = False
    value = ""
    while True:
        frase = str(input(msg))
        if frase.isalpha() and len(frase) >= 12:
            value = str(frase)
            valido = True
        else:
            print("\033[0;31mOPS! Valores inválidos ou nome curto demais.\033[m")
        if valido:
            break
    return value


nome_completo = nome("Digite seu nome completo: ")
print("Seja muito bem-vindo, {0}. ".format(nome_completo))
  • 2

    Change frase.isalpha() for all(n.isalpha() for n in frase.split(" ")) .

1 answer

2


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.

  • Oops! Very nice comet, thank you.

Browser other questions tagged

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