Checking whether a string is a number in Python is one of the most common tasks you will meet when handling user input, CSV files, API responses, or scraped data. The fastest reliable method is wrapping the conversion in a try/except block, while string methods like isdigit() and regular expressions work well when you only need a quick validation without converting the value. Below is a complete, practical guide that walks through every approach, explains the trade-offs, and shows you which one to pick for a given situation That's the part that actually makes a difference..
Why This Check Matters
Raw data is messy. 5", "N/A", " 42 ", or even "-". In practice, a column that should contain ages might hold "25", "25. If you pass those straight into arithmetic, your program crashes with a ValueError. Validating first keeps your pipelines stable, your logs readable, and your users free from ugly tracebacks Small thing, real impact. Less friction, more output..
Before choosing a method, ask yourself two questions:
- Do I need the numeric value afterwards, or only a yes/no answer?
- Which number formats must I accept: negatives, decimals, scientific notation, Unicode digits?
The answers decide everything.
The Most Reliable Method: try / except
Python's philosophy is easier to ask forgiveness than permission. Attempting the conversion and catching the exception is both accurate and fast, because it uses the same parser that will actually consume the value That's the part that actually makes a difference..
def is_number(value):
try:
float(value)
return True
except (ValueError, TypeError):
return False
print(is_number("42")) # True
print(is_number("-3.14")) # True
print(is_number("1e-5")) # True
print(is_number("abc")) # False
print(is_number(None)) # False
Note the TypeError in the exception tuple. float(None) raises TypeError, not ValueError, so a function that only catches ValueError will still crash on None or a list.
Distinguishing integers from floats
If your logic depends on whole numbers, convert to int first and fall back to float:
def classify_number(value):
try:
int(value)
return "integer"
except (ValueError, TypeError):
pass
try:
float(value)
return "float"
except (ValueError, TypeError):
return "not a number"
The NaN and infinity trap
float("nan"), float("inf"), and float("-Infinity") all succeed, yet none of them behave like ordinary numbers in comparisons. Guard against them when correctness matters:
import math
def is_finite_number(value):
try:
return math.isfinite(float(value))
except (ValueError, TypeError):
return False
print(is_finite_number("nan")) # False
print(is_finite_number("inf")) # False
print(is_finite_number("9.81")) # True
Built-in String Methods
Python ships three similar-looking methods that are not interchangeable. Understanding their differences saves hours of debugging.
| Method | Accepts "123" | Accepts "²" | Accepts "½" | Accepts "-5" | Accepts "3.isdigit() | ✅ | ✅ | ❌ | ❌ | ❌ |
| str.14" |
|---|---|---|---|---|---|
| str.isnumeric() | ✅ | ✅ | ✅ | ❌ | ❌ |
| `str.
"²".isdigit() # True -> superscript, float("²") fails
"½".isnumeric() # True -> vulgar fraction, float("½") fails
"123".isdecimal() # True -> safest for strict base-10 digits
The key takeaway: isdecimal() is the strictest and closest to what int() accepts, while isdigit() and isnumeric() are broader because they follow Unicode definitions. None of them accept signs, decimal points, or whitespace, so they suit integer-only fields such as IDs, zip codes, or loop counters.
It sounds simple, but the gap is usually here.
A practical combination for signed integers:
def is_integer_string(s):
s = s.strip()
return (s[1:] if s[:1] in "+-" else s).isdecimal()
Regular Expressions for Full Control
When you need to define exactly which shapes are valid, a compiled pattern is the cleanest solution.
import re
NUMBER_RE = re.compile(r'^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?