Checking if a string can be converted to float in Python
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Python has no built-in is_float() function. The standard way to check if a string can be converted to a float is to attempt the conversion with float() inside a try/except block. If it raises ValueError, the string is not a valid float. Alternative approaches include regex matching and custom validation functions, but the try/except pattern is the most Pythonic and handles all edge cases (scientific notation, infinity, NaN). This article covers all methods with their trade-offs.
Method 1: try/except (Recommended)
The try/except approach is the most reliable because it uses the same float() parser that you would use for the actual conversion. It handles all valid float formats including scientific notation, negative numbers, infinity, and NaN.
Method 2: str.replace + isdigit
This approach is fragile — it misses scientific notation, infinity, and NaN. Prefer try/except unless you need to reject those formats intentionally.
Method 3: Regular Expression
Regex gives fine-grained control over what you accept. This pattern handles scientific notation but rejects inf and nan, which may be desirable for data validation.
Converting After Checking
If you are going to convert anyway, skip the check and just handle the exception. Checking first and then converting calls float() twice.
Handling Special Values
Use math.isfinite() after conversion to reject infinity and NaN if your application requires finite numbers only.
Batch Validation
pd.to_numeric(errors='coerce') converts valid values and replaces invalid ones with NaN, which is often cleaner than manual filtering.
Common Pitfalls
- "nan" and "inf" are valid floats:
float("nan")andfloat("inf")do not raise exceptions. If you need only finite numbers, check withmath.isfinite()after conversion. - Whitespace handling:
float(" 3.14 ")works (strips whitespace automatically), butfloat("3 .14")raises ValueError. Leading/trailing whitespace is fine, embedded whitespace is not. - Locale-specific decimal separators:
float("3,14")raises ValueError because Python uses.as the decimal separator. For locale-aware parsing, uselocale.atof(). - Checking then converting is redundant: Calling
is_float(x)thenfloat(x)parses the string twice. If you need the value, just convert inside try/except. - Empty strings and None:
float("")raises ValueError andfloat(None)raises TypeError. The try/except approach handles both, but regex or manual checks may miss TypeError.
Summary
- Use
try: float(value)/except ValueErroras the standard check — it handles all valid formats - Use
math.isfinite()after conversion to reject infinity and NaN - Regex gives fine-grained control but misses edge cases that
float()handles - Manual string checks (
isdigit,replace) are fragile and miss scientific notation - For batch data, use
pd.to_numeric(errors='coerce')to convert valid values and NaN-fill invalid ones - If you need the value anyway, skip the check and just handle the exception directly

