How to Check if a String is Numeric in Python

This code provides a function to determine if a string represents a valid numeric value using Python's built-in float() conversion.

Easy Python 3.9+ Aug 9, 2026 Strings & text 14 views 0 copies

Python code

12 lines
Python 3.9+
def is_numeric(s):
    """Check if a string represents a valid numeric value."""
    try:
        float(s)
        return True
    except (ValueError, TypeError):
        return False

if __name__ == "__main__":
    test_cases = ["123", "-45.67", "3.14e10", "0x1A", "abc", "12.5.6", "  42  ", ""]
    for case in test_cases:
        print(f"'{case}' -> {is_numeric(case)}")

Output

stdout
'123' -> True
'-45.67' -> True
'3.14e10' -> True
'0x1A' -> False
'abc' -> False
'12.5.6' -> False
'  42  ' -> True
'' -> False

How it works

The is_numeric function attempts to convert the input string to a float. If the conversion succeeds, it returns True; if it raises ValueError or TypeError, it returns False. This approach handles integers, floats, scientific notation, and whitespace-padded strings, but does not recognize hex, binary, or other number formats as numeric.

Common mistakes

  • Using `str.isdigit()` which fails on negative numbers, decimals, and scientific notation.
  • Forgetting to catch `TypeError` when input might be `None` or a non-string.
  • Assuming the function handles hex or binary strings when it doesn't.

Variations

  1. Use `int(s, 0)` to detect integers including hex/octal/binary prefixes.

Real-world use cases

  • Validating user input from a form before converting to a number for calculations.
  • Checking if a configuration value read from a file is numeric before parsing.
  • Filtering data rows in a CSV where a field should be numeric to avoid errors.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.