How to Check If a String Contains Only Digits in Python
Validating text input is a common task in Python, especially when dealing with user inputs like PIN codes, user IDs, or phone numbers. The goal is often to ensure a string consists only of numerical digits (0-9) without any letters, spaces, or punctuation.
This guide explores the built-in string methods isdigit(), isdecimal(), and isnumeric(), explains their subtle differences regarding Unicode and special characters, and provides a robust solution for handling negative numbers and decimals.
Method 1: Using isdigit() (Standard Approach)
The isdigit() method is the most common way to check for digits. It returns True if all characters in the string are digits and there is at least one character. It returns False if the string contains spaces, letters, punctuation, or is empty.
# ✅ Valid digit string
pin_code = "12345"
print(f"'{pin_code}' contains only digits: {pin_code.isdigit()}")
# ⛔️ Invalid: Contains letters
user_id = "123ab"
print(f"'{user_id}' contains only digits: {user_id.isdigit()}")
# ⛔️ Invalid: Contains spaces
phone = "123 456"
print(f"'{phone}' contains only digits: {phone.isdigit()}")
Output:
'12345' contains only digits: True
'123ab' contains only digits: False
'123 456' contains only digits: False
An empty string "" will return False when calling .isdigit().
Method 2: Handling Negative Numbers and Floats
A common pitfall is assuming isdigit() works for all numbers. It checks for digit characters, not mathematical validity. Therefore, negative signs (-) and decimal points (.) are considered non-digits.
Problem
negative_num = "-123"
float_num = "12.34"
# ⛔️ Incorrect: These return False because '-' and '.' are not digits
print(f"Negative check: {negative_num.isdigit()}")
print(f"Float check: {float_num.isdigit()}")
Output:
Negative check: False
Float check: False
Solution: Try-Except Block
To check if a string represents a valid number (including negatives and floats), try converting it.
def is_valid_number(s):
try:
float(s) # Try converting to a number
return True
except ValueError:
return False
# ✅ Correct: Handles signs and decimals
print(f"'-123' is a number? {is_valid_number('-123')}")
print(f"'12.34' is a number? {is_valid_number('12.34')}")
Output:
'-123' is a number? True
'12.34' is a number? True
Method 3: isdecimal() vs isdigit() vs isnumeric()
Python provides three methods that seem similar but handle Unicode characters differently.
isdecimal(): Strictest. Only supports characters used to form numbers in base 10 (0-9). Best forint()conversion.isdigit(): Supports decimals plus compatibility characters like superscripts (²).isnumeric(): Widest support. Includes fractions (1/2) and Roman numerals.
# Standard "0"
val_basic = "0"
# Superscript "2" (like x²)
val_power = "\u00B2"
# Vulgar fraction "½"
val_frac = "\u00BD"
print(f"{val_basic}: Dec={val_basic.isdecimal()}, Dig={val_basic.isdigit()}, Num={val_basic.isnumeric()}")
print(f"{val_power}: Dec={val_power.isdecimal()}, Dig={val_power.isdigit()}, Num={val_power.isnumeric()}")
print(f"{val_frac}: Dec={val_frac.isdecimal()}, Dig={val_frac.isdigit()}, Num={val_frac.isnumeric()}")
Output:
0: Dec=True, Dig=True, Num=True
²: Dec=False, Dig=True, Num=True
½: Dec=False, Dig=False, Num=True
If you plan to convert the string to an integer immediately after checking, use isdecimal(). Converting a superscript ² or fraction ½ using int() will raise a ValueError, even though isdigit() or isnumeric() returns True.
Method 4: Using Regular Expressions
If you need specific validation rules (e.g., "digits only, exactly 5 characters"), Regular Expressions (re) are more powerful than string methods.
import re
text = "12345"
# ✅ Check if string contains ONLY digits (one or more)
if re.fullmatch(r'\d+', text):
print("Regex match: Digits only")
else:
print("Regex match: Contains other characters")
Output:
Regex match: Digits only
Conclusion
To check if a string contains digits in Python:
- Use
str.isdigit()for standard checks (PINs, IDs) where only characters 0-9 are allowed. - Use
str.isdecimal()if you strictly intend to convert the string to an integer later, avoiding Unicode surprises. - Use
try-except float()if you need to validate mathematical numbers containing negatives or decimals.