How do you reliably check if a string represents a valid integer or float in Python? | A1Lab@MZeeshanM to PythonEnglish • 4 days ago

How do you reliably check if a string represents a valid integer or float in Python?

message-square
0

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(), and str.isnumeric() are unreliable for number parsing:
    • All three return False for negative signs ("-5"), plus signs ("+5"), decimal points ("3.14"), scientific notation ("1e10"), and leading/trailing whitespace (" 42 ").
    • Conversely, str.isdigit() returns True for "2³" (which raises ValueError in int("2³")), and str.isnumeric() returns True for "½" and "Ⅳ" (which also fail int() and float()).
  • float() accepts "nan", "inf", and "-infinity" by default:
    • float("nan"), float("inf"), and float("Infinity") succeed without raising ValueError (case-insensitively). In user input, JSON, or CSV validation, "nan" (such as the surname "Nan") or "inf" can slip through unless you check math.isfinite(val) (which returns False for NaN, +inf, and -inf).
  • Underscore separators ("1_000") and whitespace (" 42\n"):
    • Both int("1_000") and float("3.14_15") return True in 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, or re.fullmatch(r"[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?", s) for standard decimal/scientific floats).
  • Guard against non-string inputs (bool, int, float, None):
    • Calling int(True) returns 1 and float(None) raises TypeError (not ValueError). Always check isinstance(s, str) first—or catch (ValueError, TypeError) if arbitrary types may be passed—so non-string objects don’t unexpectedly pass validation or crash with TypeError.
  • Whole-number floats like "3.0" vs. strict integers "3":
    • is_integer("3.0") returns False because int("3.0") raises ValueError. If you want "3.0" to count as an integer value, parse as float first and check val.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.