I'm updating my answer to simplify the code and make it more readable.
The below function is a function that I would use in my own code, I would consider it to be more "proper" than my old answer.
from string import ascii_letters
def get_name():
name = input("What is your name?\n: ").strip().title()
while not all(letter in ascii_letters + " -" for letter in name):
name = input("Please enter a valid name.\n: ").strip().title()
return name
To break this down, the line all(letter in ascii_letters + " -" for letter in name)
means "if each letter in name is not an alphabetical character, a space, or a hyphen".
The part letter in ascii_letters + " -"
checks to see if a letter is in the string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -"
.
This is repeated by the next part, for letter in name
, for every character in the string. This will effectively return a list of booleans, [True, True, True, ...]
where any False
is a character that did not pass the conditional. Next, this list is passed to the all()
function, which returns True
if all of the list items are True
.
After the all()
is executed, conditional is reversed, allowing the loop to continue on the existence of a single failed character.
Old answer is as follows, it will still be useful.
This function should work well for you. Simply check if the string the user entered is alpha characters only, otherwise ask again.
Notice the use of str.isalpha()
.
def get_name():
name = input("What is your name?\n: ").strip().title()
while not (name.replace("-", "") and
name.replace("-", "").replace(" ", "").isalpha()):
name = input("Please enter a valid name.\n: ").strip().title()
return name
Checking if name
will check if the string is empty, and using str.strip()
on the values returned will remove any surrounding whitespace (stray spaces) to the left or right of the user input.
The str.replace("-", "")
eliminates hyphens while checking validity. Thanks for pointing this out @AGN Gazer.
Now you can just call the function later in your script, or store it for later.
name = get_name().title()
print("You said your name was " + name + ".)
The str.title()
converts the letter of each word in a string to uppercase. For example, if I entered my name "jacob birkett", the output (and subsequent value of name
would be "Jacob Birkett".
Take a look at the documentation for str.isalpha()
, str.strip()
, str.replace()
and str.title()
.