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.
Python code
12 linesdef 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
'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
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.