Home > Back-end >  How to restrict python input to only allow letters and space
How to restrict python input to only allow letters and space

Time:09-01

This is my current code:

while True:
    name = input("Please enter your name: ")
    if name.isalpha() and name.isspace(): #fix to allow space
        break
    if name.isalpha():
        break
    else:
        print("Error")

The issue is that it raises an error if the input is "Bob Dole", as the inputs of "Bob" or "James" is working fine. How do I make sure it allows a full name esque input?

CodePudding user response:

This will test by character instead of by word as you're currently doing;

if all((char.isalpha() or char==' ') for char in name):

CodePudding user response:

Instead, use two validations, use the or clause and check each character that you received from input, for example:

while True:
    name = input("Please enter your name: ")
    if all(x.isalpha() or x.isspace() for x in name):
        break
    else:
        print("Error")

CodePudding user response:

isalpha and isspace functions check if the string ONLY comprises of alpha and space characters, respectively. A "Bob Dole" string will return False to both isalpha and isspace functions.

You may have to use isalpha and isspace functions on each letter of the name, and use all function to check if all characters satisfy the condition. Alternatively, you can just use for/while loop to iterate each letter and check against isalpha and isspace accordingly.

while True:
    name = input("Please enter your name: ")
    if all([letter.isalpha() or letter.isspace() for letter in name]):
        break
    else:
        print("Error")

CodePudding user response:

From @wkl's comment...

while True:
     name = input("Please enter your name: ")
     if name.isalpha():
          break
     if all(each.isalpha() for each in name.split()):
          break
     else:
          print("Error")

This should work just fine :)

  • Related