Kodeclik Blog
Python String isdigit() method
Sometimes you will encounter a situation where you will need to check if the characters in a string are digits. For instance, let us suppose you are writing a program that solicits the user for input about their age and you wish to check if the age that was input comprises only digits. Here is how that might work.
The key in the above program is the validate_age() function. It implements a basic approach to digit validation using character comparison. In Python, characters can be compared using relational operators because each character has an underlying ASCII or Unicode value. When we compare char < '0' or char > '9', we're actually comparing the character's ordinal value with the ordinal values of '0' (48 in ASCII) and '9' (57 in ASCII). Any character that falls outside this range is not a digit.The only characters that fall within this range will be the actual numbers like 0, 1, 2, …9.
If we try this program like so:
we will get the output:
This is because 25 is a valid age, but 12.5 and 18a are not.
Using Python isdigit()
Think of Python’s isdigit() method as a shorthand to achieve the same objective. Here is how that works:
Note that the validate_age function has been simplified to use isdigit() while maintaining the same validation rules. The function combines two checks: bool(input_string) ensures the string is not empty, and input_string.isdigit() verifies that all characters are digits. The get_age() function is the same as before because only the validation code has changed.
If we try this program like so:
we will get:
Isn’t this more convenient? Note that isdigit() requires the string to be non-empty. For the last attempt at using validate_age(), it returns False because we have supplied an empty string.
Phone Number Validator
Here is a US phone number validator program that checks if the input string resembles a US phone number, ie area code followed by seven digits. Note that phone numbers are written in various forms, sometimes with spaces, hyphens, and brackets. We need to account for all of them.
The validate_phone_number function handles multiple common phone number formats. It first removes all formatting characters (spaces, parentheses, and hyphens) and then checks two conditions. It makes sure the cleaned up string is exactly 10 digits long and all remaining characters must be digits using isdigit().
The output will be:
This validator is quite practical as it handles many real-world phone number inputs while maintaining simple and clear validation logic using only string replacements and isdigit().
Social Security Number Validator
Let us now write a social security number (SSN) validator using isdigit(). A valid SSN consists of exactly nine digits, typically formatted as XXX-XX-XXXX in standard notation.
As before we first remove any formatting characters (spaces and hyphens) using the replace method, and then verify two key conditions: the cleaned string must be exactly 9 characters long, and all characters must be digits using isdigit().
Note that the test cases evaluate our function’s ability to handle many different formats and edge cases. The output will be:
Of course, in a production system, you will have additional checks to ensure that these are actually valid SSN numbers. This way you can exclude invalid SSN combinations like all zeros or known invalid patterns.
Digit String Separator
Let us write a digit string separator that goes through a string and picks out sequences of digits and organizes them into a list.
As mentioned, the digit_string_separator function processes a text string and extracts sequences of consecutive digits, returning them as separate elements in a list. It maintains a current_number variable that accumulates digits until a non-digit character is encountered. When a non-digit appears, if current_number contains any accumulated digits, it's added to the result list and reset.
The function handles various text patterns, extracting pure number sequences regardless of their surrounding context. For example, from "abc123def456" it extracts ["123", "456"], and from "price: 50 quantity: 5" it extracts ["50", "5"]. The final check after the loop ensures that any trailing number sequence is also captured.
This function is particularly useful for extracting numerical data from mixed text, such as processing documents, logs, or any text that contains embedded numbers.
If we use this function like so:
The output will be:
ZIP Code Validator
Let us write a zip code validator that checks to see if a supplied zip code is in the standard 5 digit, or 5+4 digit format.
As mentioned above, the validate_zip_code function handles both standard 5-digit ZIP codes and the extended ZIP+4 format. It first removes any spaces from the input, then checks for two valid patterns: either a 5-digit code (like "12345") or a 9-digit code separated by a hyphen (like "12345-6789"). For the ZIP+4 format, the function splits the string at the hyphen position and verifies that both parts contain only digits - the first part must be 5 digits and the second part must be 4 digits.
The output will be:
Again, note that “12345” might or might not be a real zip code in the US. To do such semantic checking, you need to have more domain knowledge.
Room number validator
Finally, let us write a room number validator to check if a given string is a room number. A room number should be an optional letter followed by a three digit number, eg. “A123”, or “B456”. The first letter denotes the “floor number”. (If no letter is provided, it means the number is on the main or ground level.)
As mentioned, the room number validator is designed to handle two common formats of room numbers found in buildings and hotels: either a pure three-digit number (like "101") or a letter followed by three digits (like "A101") where the letter typically represents a floor or wing designation.
The validate_room_number function first checks if the input starts with a letter; if it does, it separates the first character and validates that the remaining portion contains exactly three digits using isdigit(). If there's no leading letter, it checks if the entire input is a three-digit number.
This flexible validation allows for both simple numeric room numbers and those with floor/wing indicators while maintaining strict length requirements.
If we run the above program we will get the following output for our test cases:
We hope this gives you an idea of the isdigit() approach to check if a character is a digit and the versatile ways in which it can be used. If you liked reading so far, learn about Python’s isnumeric() method which is a little bit more general than isdigit(). Also while we are on the topic of processing strings, learn how to remove the last character from a Python string.
Enjoy this blogpost? Want to learn Python with us? Sign up for 1:1 or small group classes.