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.
def validate_age(input_string):
# Return False if string is empty
if not input_string:
return False
# Check each character
for char in input_string:
if char < '0' or char > '9':
return False
return True
# Example usage
def get_age():
while True:
age = input("Please enter your age: ")
if validate_age(age):
return int(age)
print("Invalid age! Please enter only digits.")
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:
# Test the validation
print(validate_age("25"))
print(validate_age("12.5"))
print(validate_age("18a"))
we will get the output:
True
False
False
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:
def validate_age(input_string):
return input_string.isdigit()
def get_age():
while True:
age = input("Please enter your age: ")
if validate_age(age):
return int(age)
print("Invalid age! Please enter only digits.")
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:
print(validate_age("25"))
print(validate_age("12.5"))
print(validate_age("18a"))
print(validate_age(""))
we will get:
True
False
False
False
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.
def validate_phone_number(phone):
# Remove spaces, brackets, and hyphens
phone = phone.replace(" ", "")
phone = phone.replace("(", "")
phone = phone.replace(")", "")
phone = phone.replace("-", "")
if len(phone) == 10 and phone.isdigit():
return True
return False
# Test cases
print("Testing phone number formats:")
test_numbers = [
"1234567890", # Basic 10 digits
"123 456 7890", # Spaces
"(123) 456-7890", # Standard US format
"123-456-7890", # Hyphenated
"(123)456-7890", # No space after parentheses
"(123) 456 7890", # Mixed format
"12345", # Too short
"123456789012", # Too long
"abcd567890", # Contains letters
"(12a) 456-7890" # Contains letter within
]
for number in test_numbers:
result = validate_phone_number(number)
print(f"Number: {number:15} -> Valid: {result}")
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:
Testing phone number formats:
Number: 1234567890 -> Valid: True
Number: 123 456 7890 -> Valid: True
Number: (123) 456-7890 -> Valid: True
Number: 123-456-7890 -> Valid: True
Number: (123)456-7890 -> Valid: True
Number: (123) 456 7890 -> Valid: True
Number: 12345 -> Valid: False
Number: 123456789012 -> Valid: False
Number: abcd567890 -> Valid: False
Number: (12a) 456-7890 -> Valid: False
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.
def validate_ssn(ssn):
# Remove spaces and hyphens
ssn = ssn.replace(" ", "")
ssn = ssn.replace("-", "")
if len(ssn) == 9 and ssn.isdigit():
return True
return False
# Test cases
test_ssns = [
"123456789", # Basic 9 digits
"123-45-6789", # Standard format
"123 45 6789", # Spaces format
"123-456789", # Partial hyphenation
"123 456-789", # Mixed format
"12345678", # Too short
"1234567890", # Too long
"12a-45-6789", # Contains letter
"000-00-0000", # All zeros
"123456", # Incomplete
"abc-de-fghi" # All letters
]
for ssn in test_ssns:
result = validate_ssn(ssn)
print(f"SSN: {ssn:12} -> Valid: {result}")
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:
SSN: 123456789 -> Valid: True
SSN: 123-45-6789 -> Valid: True
SSN: 123 45 6789 -> Valid: True
SSN: 123-456789 -> Valid: True
SSN: 123 456-789 -> Valid: True
SSN: 12345678 -> Valid: False
SSN: 1234567890 -> Valid: False
SSN: 12a-45-6789 -> Valid: False
SSN: 000-00-0000 -> Valid: True
SSN: 123456 -> Valid: False
SSN: abc-de-fghi -> Valid: False
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.
def separate_digits(text):
result = []
current_number = ""
for char in text:
if char.isdigit():
current_number += char
elif current_number:
if current_number.isdigit():
result.append(current_number)
current_number = ""
if current_number and current_number.isdigit():
result.append(current_number)
return result
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:
text = "abc123def456ghi789"
print(separate_digits(text))
text2 = "price: 50 quantity: 5"
print(separate_digits(text2))
The output will be:
['123', '456', '789']
['50', '5']
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.
def validate_zip_code(zip_code):
# Remove any spaces
zip_code = zip_code.replace(" ", "")
# Handle basic 5-digit format
if len(zip_code) == 5 and zip_code.isdigit():
return True
# Handle ZIP+4 format
if len(zip_code) == 10 and zip_code[5] == "-":
first_part = zip_code[:5]
last_part = zip_code[6:]
if first_part.isdigit() and last_part.isdigit():
return True
return False
# Test cases
test_zips = [
"12345", # Basic 5-digit
"12345-6789", # ZIP+4 format
"12345 6789", # Space instead of hyphen
"1234", # Too short
"123456", # Too long but no hyphen
"12345-678", # Incomplete ZIP+4
"1234-56789", # Wrong format
"abcde", # Letters only
"12345-abcd", # Letters in extension
"12345-67890", # Too many digits in extension
"123456789", # 9 digits but no hyphen
"12345 - 6789" # Extra spaces
]
for zip_code in test_zips:
result = validate_zip_code(zip_code)
print(f"ZIP: {zip_code:12} -> Valid: {result}")
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:
ZIP: 12345 -> Valid: True
ZIP: 12345-6789 -> Valid: True
ZIP: 12345 6789 -> Valid: False
ZIP: 1234 -> Valid: False
ZIP: 123456 -> Valid: False
ZIP: 12345-678 -> Valid: False
ZIP: 1234-56789 -> Valid: False
ZIP: abcde -> Valid: False
ZIP: 12345-abcd -> Valid: False
ZIP: 12345-67890 -> Valid: False
ZIP: 123456789 -> Valid: False
ZIP: 12345 - 6789 -> Valid: True
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.)
def validate_room_number(room):
# Remove any floor indicator letter if present
if room and room[0].isalpha():
floor_letter = room[0]
room_number = room[1:]
return room_number.isdigit() and len(room_number) == 3
return room.isdigit() and len(room) == 3
# Test cases
test_rooms = [
"101", # Valid basic room
"A101", # Valid with floor letter
"B203", # Valid with floor letter
"1234", # Invalid length
"10", # Invalid length
"ABC", # Invalid all letters
"A1B2", # Invalid mixed
"" # Invalid empty
]
for room in test_rooms:
result = validate_room_number(room)
print(f"Room: {room:6} -> Valid: {result}")
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:
Room: 101 -> Valid: True
Room: A101 -> Valid: True
Room: B203 -> Valid: True
Room: 1234 -> Valid: False
Room: 10 -> Valid: False
Room: ABC -> Valid: False
Room: A1B2 -> Valid: False
Room: -> Valid: False
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.