Skip to content Skip to sidebar Skip to footer

Prevent Input() From Being Anything But Alphabet Characters

I am attempting to make a program for the sake of self-knowledge. I want to ask the user what their name is, and I only want the user to be able to use letters from the alphabet to

Solution 1:

You can enforce this requirement using str.isalpha. From the documentation:

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard.

Here is an example program:

whileTrue:
    name = input('Enter a name using only alphabetic characters: ')
    if name.isalpha():
        break

Demo:

Enter name usingonly alphabetic characters:  Bo2
Enter name usingonly alphabetic characters:  Bo^&*(
Enter name usingonly alphabetic characters:  Bob

Note this method will not work for people with hyphenated names such as "Anne-Marie".

Solution 2:

I agree that this question is a little misleading. However, with what you have said, you just need to use a regex to accomplish this.

import re
...
if not re.findall('[^a-zA-Z]', 'abc1'):
   print("You have entered a name correctly.")
elseprint("Your name cannot be an integer. Try again.")
   cc()

Post a Comment for "Prevent Input() From Being Anything But Alphabet Characters"