Skip to content Skip to sidebar Skip to footer

In Python, How Do I Check That The User Has Entered A Name Instead Of A Number?

In Python, how do I check that the user has entered a name instead of a number, when asking for user input as string? I want a string input in the form of their name, but I want to

Solution 1:

Depending on the exact requirements for being a name and not a number, you can probably just call .isalpha() on the string you get from the user.

See the docs for assorted methods to check whether a string satisfies certain criteria.

Solution 2:

You can define a function that determines if there are any non-alphabetic characters in the input string:

def is_valid_name(s):
    return all(char.isalpha() forchar in s)

This will return True if only alphabetic characters exist in the string, False otherwise.

>>> print(is_valid_name("Hello123"))
False>>> print(is_valid_name("Hello"))
True

Note that this doesn't work with spaces:

>>> print(is_valid_name("Hello World"))
False

So it can be adjusted if necessary:

def is_valid_name(s):
    returnall(char.isalpha() orchar.isspace() forcharin s)

See here:

>>> print(is_valid_name("Hello World"))
True

Solution 3:

If you wanna check correct in english dictionary then you can use pyenchant ... use pip to install it ... its east to use and gives true if spelling of a word is correct and false if word doesn't exist in english dictionary.

pip install pyenchant

Post a Comment for "In Python, How Do I Check That The User Has Entered A Name Instead Of A Number?"