Check whether a Python string represents a number
Choose integer, floating-point, or digit validation in Python. Handle signs, Unicode digits, NaN, infinity, and conversion errors explicitly.
Choose the numeric format your application accepts, then attempt that conversion. int(text) checks integer syntax; float(text) accepts decimal and exponent notation. A character test such as isdigit() answers a different question and is not a general integer parser.
Parse the intended type
def is_float_string(text):
if not isinstance(text, str):
return False
try:
float(text)
except ValueError:
return False
return True
print(is_float_string("-12.3")) # True
print(is_float_string("1e5")) # True
print(is_float_string("abc")) # False
float() also accepts surrounding whitespace, "nan", and "inf". If your input must be finite, inspect the converted value:
import math
value = float("12.3")
if not math.isfinite(value):
raise ValueError("A finite number is required")
For an integer, convert with int(text) directly rather than converting through a float, which can lose precision or truncate fractional values. Keep conversion and validation in the same try block instead of parsing twice.
Understand the character tests
print("123".isdigit()) # True
print("-123".isdigit()) # False
print("12.3".isdigit()) # False
print("²".isdigit()) # True
print("²".isdecimal()) # False
print("⅓".isnumeric()) # True
isdecimal() is the narrowest of these Unicode character classifications, followed by isdigit() and isnumeric(). All require a nonempty string, and none accepts a leading sign or decimal point. A superscript digit can pass isdigit() but still fail int().
If a field must contain only ASCII decimal digits, use text.isascii() and text.isdecimal(). For money or other exact decimal requirements, consider decimal.Decimal with an explicit policy for finite values and precision.
FAQ
Why not isinstance(text, int)? That checks the existing object's type. A string containing digits is still a string.
Is float() a complete number validator? No. Its accepted syntax and special values may be broader than your field's rules. Apply domain constraints after parsing, or validate a stricter grammar before conversion.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan