Explain Codes LogoExplain Codes Logo

How do I parse a string to a float or int?

python
error-handling
input-validation
float-parsing
Anton ShumikhinbyAnton Shumikhin·Feb 13, 2025
TLDR

For an immediate solution, use int() for whole number strings and float() for those with decimal component. For versatility, a try-except block can attempt to parse to int and default to float when it hits a snag:

def parse_number(s): try: return int(s) # Castles in the sky except ValueError: return float(s) # Sunset by the beach num_int = parse_number("42") # Returns int: 42 num_float = parse_number("3.14") # Returns float: 3.14

Parsing across locales

Got a string in local numeric format, like "3,14" as 3.14? Python's locale library to the rescue! Just set the locale correctly:

import locale locale.setlocale(locale.LC_NUMERIC, 'de_DE') # Ready for a German vacation num = locale.atof("3,14") # Returns float: 3.14

Always remember to set locales aptly before parsing to match the numeric string format.

Cure-all: Error handling & input validation

Ensure that your string can transmute into a float before the conversion and use a try-except block to handle slips gracefully:

def safe_parse(s): try: return int(s) # Wishful thinking except ValueError: try: return float(s) # Falling back except ValueError: return None # Or tailor this to handle "oops" moments print(safe_parse("not a number")) # None or your error message!

Opt for ast.literal_eval() to safely evaluate numeric strings:

import ast def safe_eval(s): try: return ast.literal_eval(s) # Much safer than eval() except (ValueError, SyntaxError): return None # Bad input, no biscuit! safe_eval("2.71828") # Returns 2.71828

Handling special float values & precision quirks

Sometimes, you might get a wildcard NaN or ±inf when dealing with floats. Be prepared to catch these curveballs:

def handle_special_floats(s): try: f = float(s) if not (math.isnan(f) or math.isinf(f)): return f # It's a good float! except ValueError: pass return None # Expeliarmus! handle_special_floats("nan") # None handle_special_floats("inf") # None

Watch out for precision issues resulting from binary storage. Be prepared for a "close but not quite" dance.

Checking float potential

To establish if a given string can indeed transform into a float, you can use a dedicated function:

def is_float(value): try: float(value) return True # Success! except ValueError: return False # Not on my float! is_float("123.45") # True, let me get my swimsuit! is_float("abc") # False, looks like dry land here.

Strings to integers: Best practices

Always clean up the string before conversion to integer. Remove whitespace and other potential noise:

num = int(" 42 ".strip()) # Tidying up: Returns 42

Under Python 2, unicode and hexadecimal are valid, while Python 3 welcomes underscores in numeric literals:

num = int("0xA", 16) # Hex appeal: Returns 10 num = int("1_000_000") # Underscore charisma: Returns 1000000

Old isn't gold: Python version differences

Different Python versions, different parsing behavior. Always triage your code for the target Python version. For instance, Python 2 and 3 handle Unicode and byte strings differently.

Exceptional exceptions in critical applications

For mission-critical applications where accuracy can't be compromised, consider using fixed-point arithmetic or Python's decimal module. Float parsing could induce a bad trip!

Cleanliness is next to parsedliness: Check string inputs

Validate string inputs for cleanliness and correct encoding, especially if you're dealing with Unicode strings in Python 2. Keep your parsing life bug-free.

Advanced formats 101

Python can interpret advanced numeric formats, including scientific notation and hexadecimal inside of a string. Brace for interpretations!