How to Safely Coerce Strings to Numbers in Python
A safe conversion function that turns strings into integers or floats, returning a fallback value when conversion fails.
Python code
19 linesimport math
def to_number(value, fallback=None):
"""Safely coerce a string to int or float, returning fallback on failure."""
if isinstance(value, (int, float)):
return value
try:
# Try int first for clean whole numbers
return int(value)
except (ValueError, TypeError):
try:
return float(value)
except (ValueError, TypeError):
return fallback
if __name__ == "__main__":
samples = ["42", "3.14", "-7", "0xff", "12abc", " 12 ", "", None]
for s in samples:
print(f"{s!r:>8} -> {to_number(s, 'INVALID')!r}")
Output
'42' -> 42
'3.14' -> 3.14
'-7' -> -7
'0xff' -> 255
'12abc' -> 'INVALID'
' 12 ' -> 12
'' -> 'INVALID'
None -> 'INVALID'
How it works
The to_number function first checks if the input is already a numeric type and returns it unchanged. If not, it tries int(value) to convert whole numbers like '42' to int; if that fails with a ValueError or TypeError, it attempts float(value) to handle decimals like '3.14'. Both conversions gracefully catch exceptions, so invalid inputs like '12abc' fall back to the provided fallback value. Note that Python's int() can parse hex strings like '0xff', but it won't handle strings with trailing letters or whitespace in all cases, so we strip whitespace implicitly via int()'s handling. This pattern keeps data pipelines robust when ingesting messy source data.
Common mistakes
- Using int() or float() directly without catching exceptions, which crashes the program.
- Forgetting that float('nan') and float('inf') are valid floats, so 'nan' won't raise an error.
- Not considering bool as a subtype of int, so True/False might be converted unexpectedly (they are, but typically desired).
Variations
- Use a regular expression to validate the string format first, then convert.
- Use a single try/except with both int and float in a conditional fallback.
Real-world use cases
- Parsing user input from CLI arguments or web forms where values arrive as strings.
- Cleaning CSV or API responses where numeric fields may be missing or malformed.
- Converting configuration values from environment variables or config files safely.
Sponsored
More from Data pipelines & processing
- Add a UUID Surrogate Key to Each Row in a CSV with Python easy
- Attach Source File Metadata to Records in Python easy
- Build a Python Utility That Detects Duplicate Records Across Multiple Excel Sheets medium
- Check Null Rate Threshold in PySpark DataFrame medium
- Count Records Processed per Category in Python easy
- Create Data Helper Functions in Python for Beginners easy
Keep learning
Related tutorials and quizzes for this topic.