How to Check if a String is Numeric in Python
In Python, you can check if a string is numeric using the
str.isdigit(), str.isnumeric(), or str.isdecimal() methods. These methods return True if all characters in the string are numeric digits and False otherwise.Syntax
Python provides three main string methods to check if a string contains only numeric characters:
str.isdigit(): ReturnsTrueif all characters are digits (0-9).str.isnumeric(): ReturnsTrueif all characters are numeric, including digits and numeric characters from other languages.str.isdecimal(): ReturnsTrueif all characters are decimal characters (0-9).
python
string.isdigit() string.isnumeric() string.isdecimal()
Example
This example shows how to use isdigit(), isnumeric(), and isdecimal() to check different strings for numeric content.
python
samples = ['12345', '²345', '123.45', 'Ⅷ', '123a'] for s in samples: print(f"Checking '{s}':") print(f" isdigit(): {s.isdigit()}") print(f" isnumeric(): {s.isnumeric()}") print(f" isdecimal(): {s.isdecimal()}") print()
Output
Checking '12345':
isdigit(): True
isnumeric(): True
isdecimal(): True
Checking '²345':
isdigit(): False
isnumeric(): True
isdecimal(): False
Checking '123.45':
isdigit(): False
isnumeric(): False
isdecimal(): False
Checking 'Ⅷ':
isdigit(): False
isnumeric(): True
isdecimal(): False
Checking '123a':
isdigit(): False
isnumeric(): False
isdecimal(): False
Common Pitfalls
Many beginners expect isdigit() to return True for strings with decimal points or negative signs, but it does not. Also, isnumeric() includes numeric characters like superscripts and fractions, which may not be what you want.
To check if a string represents a valid number including decimals or negatives, use float() conversion inside a try-except block instead.
python
s = '-123.45' # Wrong way: isdigit() returns False print(s.isdigit()) # False # Right way: try converting to float try: num = float(s) print(True) except ValueError: print(False)
Output
False
True
Quick Reference
| Method | Description | Example Returns True For |
|---|---|---|
| isdigit() | Checks if all characters are digits (0-9) | '12345' |
| isnumeric() | Checks if all characters are numeric (digits + numeric chars) | '12345', '²345', 'Ⅷ' |
| isdecimal() | Checks if all characters are decimal digits (0-9) | '12345' |
Key Takeaways
Use str.isdigit() to check if a string contains only digit characters (0-9).
str.isnumeric() is broader and includes numeric characters like superscripts and fractions.
str.isdecimal() is stricter and only returns True for decimal digits.
For numbers with decimals or signs, use float conversion with try-except instead of these methods.
These methods return False for empty strings or strings with spaces or symbols.