In this article, we show how to perform string verification in Python.
With Python, we can check if an input entered in by a user is only alphabetical characters, a number, a decimal, an integer, is a space, or is a title.
When a user enters in an input in Python through the input() function, all of the contents are considered a string.
Depending on the information being asked of the user determines what verification should be done.
For example, when you ask a person for his or her name, there should only be alphabetical characters. Therefore, we verify that all characters entered in are alphabetical characters. For example, no numbers or special symbols should be entered in. If there are, this is unacceptable input and the user should re-enter in the information correctly.
If asking for a user's zip code, all numbers should be entered in.
We'll first go over how to check to see if a string is all alphabetical characters.
We do this through the isalpha() function.
The code below uses the isalpha() function to check to see if the input
entered in is all alphabetical characters or not.
You can see that "David" is all alphabetical characters. Thus, "True" is
output. "Peter1" is not all alphabetical characters, so "False" is returned.
Now we will check to see if a string is composed of all numbers.
This can be done through the isalnum() function.
This is shown in the code below.
Thus, userinput returns true with the isnumeric() function because it is all numbers, while
userinput2 returns false because it also has alphabetical characters.
We'll now show how to check if a string only contains alphabetical characters and numbers.
We do this through the isalnum() function.
This is shown in the code below.
So, you can see how the isalnum() function returns true only if the string contains only alphabetical characters and numbers.
Below can be a real-world script of a string being verified to see if it
only contains alphabetical characters. This is so that you can get a sense of how a string
may be verified in a real-life sort of like script.
Below is a table of other functions that can be used to verify a string.
Related Resources
How to Randomly Select From or Shuffle a List in Python