Wrap int(s) (for integers) or float(s) (for floats) in a try ... except ValueError: block—optionally rejecting "nan" and "inf" with math.isfinite(val) when validating real finite numbers—because Python’s built-in string methods like .isdigit() and .isnumeric() fail on negative signs, decimal points, and scientific notation ("-42", "3.14", "1e-5"), while falsely returning True for superscripts or Unicode fractions ("²", "½").
Basic Example
import math
# 1. Reliably check if a string represents a valid base-10 integer
def is_integer(s: str) -> bool:
if not isinstance(s, str):
return False
try:
int(s)
return True
except ValueError:
return False
# 2. Reliably check if a string represents a finite real number (int or float)
def is_finite_float(s: str) -> bool:
if not isinstance(s, str):
return False
try:
return math.isfinite(float(s))
except ValueError:
return False
print(is_integer("-42")) # Output: True
print(is_integer("3.14")) # Output: False
print(is_finite_float("-3.14")) # Output: True
print(is_finite_float("1e-5")) # Output: True
print(is_finite_float("nan")) # Output: False (use float(s) without isfinite() if NaN/Inf are allowed)
Key Details & Edge Cases
- Why
str.isdigit(),str.isdecimal(), andstr.isnumeric()are unreliable for number parsing:- All three return
Falsefor negative signs ("-5"), plus signs ("+5"), decimal points ("3.14"), scientific notation ("1e10"), and leading/trailing whitespace (" 42 "). - Conversely,
str.isdigit()returnsTruefor"2³"(which raisesValueErrorinint("2³")), andstr.isnumeric()returnsTruefor"½"and"Ⅳ"(which also failint()andfloat()).
- All three return
float()accepts"nan","inf", and"-infinity"by default:float("nan"),float("inf"), andfloat("Infinity")succeed without raisingValueError(case-insensitively). In user input, JSON, or CSV validation,"nan"(such as the surname"Nan") or"inf"can slip through unless you checkmath.isfinite(val)(which returnsFalseforNaN,+inf, and-inf).
- Underscore separators (
"1_000") and whitespace (" 42\n"):- Both
int("1_000")andfloat("3.14_15")returnTruein Python 3.6+ because Python supports PEP 515 numeric underscores, and both functions automatically strip leading/trailing whitespace (" 42\n"). - If your external format forbids underscores or surrounding whitespace, validate against a strict regex (e.g.,
re.fullmatch(r"[+-]?\d+", s)for ASCII integers, orre.fullmatch(r"[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?", s)for standard decimal/scientific floats).
- Both
- Guard against non-string inputs (
bool,int,float,None):- Calling
int(True)returns1andfloat(None)raisesTypeError(notValueError). Always checkisinstance(s, str)first—or catch(ValueError, TypeError)if arbitrary types may be passed—so non-string objects don’t unexpectedly pass validation or crash withTypeError.
- Calling
- Whole-number floats like
"3.0"vs. strict integers"3":is_integer("3.0")returnsFalsebecauseint("3.0")raisesValueError. If you want"3.0"to count as an integer value, parse as float first and checkval.is_integer()(math.isfinite(val) and val.is_integer()).
Comparison of String Number Validation Methods in Python
| Method | "42" |
"-3.14" |
"1e-5" |
"nan" / "inf" |
"²" / "½" |
Best Used When |
|---|---|---|---|---|---|---|
try: int(s) |
True |
False |
False |
False |
False |
Validating strings that can be parsed cleanly by int(). |
try: math.isfinite(float(s)) |
True |
True |
True |
False |
False |
Validating real numeric input (ints, decimals, scientific notation) while rejecting NaN/Inf. |
try: float(s) |
True |
True |
True |
True |
False |
Parsing IEEE 754 floats where "inf" and "nan" are valid values. |
Strict Regex (re.fullmatch) |
True |
True |
True |
False |
False |
Enforcing strict wire formats where Python-specific "1_000" underscores or spaces are disallowed. |
s.isdigit() (Avoid for parsing) |
True |
False |
False |
False |
True ("²") |
Checking raw Unicode decimal/digit characters only—never for general numeric parsing. |
You must log in or register to comment.
