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.

Easy Python 3.9+ Aug 9, 2026 Data pipelines & processing 12 views 0 copies

Python code

19 lines
Python 3.9+
import 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

stdout
'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

  1. Use a regular expression to validate the string format first, then convert.
  2. 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

Run this sample

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

Open editor

More from Data pipelines & processing

Related tutorials and quizzes for this topic.