How do I parse a string to a float or int?
Categories:
Parsing Strings to Floats and Integers in Python

Learn how to safely and effectively convert string representations of numbers into float and integer types in Python, handling common errors and edge cases.
Converting strings to numerical types (integers or floats) is a fundamental operation in programming, especially when dealing with user input, file parsing, or data from external sources. Python provides built-in functions to handle these conversions, but it's crucial to understand how to use them correctly and robustly to avoid common pitfalls like ValueError
.
Converting Strings to Integers (int()
)
The int()
constructor is used to convert a string to an integer. It takes a string as its primary argument and an optional base for the conversion. If the string does not represent a valid integer in the specified base, a ValueError
will be raised. It's important to ensure the string contains only digits (and an optional sign) for a successful conversion.
# Basic integer conversion
string_int = "123"
number_int = int(string_int)
print(f"'{string_int}' as int: {number_int}, type: {type(number_int)}")
# With a sign
string_negative_int = "-45"
negative_number_int = int(string_negative_int)
print(f"'{string_negative_int}' as int: {negative_number_int}, type: {type(negative_number_int)}")
# Conversion with a base (e.g., binary)
binary_string = "1011"
binary_number = int(binary_string, 2)
print(f"'{binary_string}' (base 2) as int: {binary_number}")
Basic usage of int()
for string to integer conversion.
int()
will result in a ValueError
. For example, int("12.3")
or int("abc")
will fail.Converting Strings to Floating-Point Numbers (float()
)
The float()
constructor converts a string to a floating-point number. This function is more flexible than int()
as it can handle decimal points, scientific notation, and even special string representations like 'inf' (infinity) and 'nan' (not a number). Like int()
, it will raise a ValueError
if the string cannot be interpreted as a valid float.
# Basic float conversion
string_float = "123.45"
number_float = float(string_float)
print(f"'{string_float}' as float: {number_float}, type: {type(number_float)}")
# With scientific notation
string_scientific = "1.23e-5"
scientific_float = float(string_scientific)
print(f"'{string_scientific}' as float: {scientific_float}")
# Special values
string_inf = "inf"
infinity_float = float(string_inf)
print(f"'{string_inf}' as float: {infinity_float}")
string_nan = "nan"
nan_float = float(string_nan)
print(f"'{string_nan}' as float: {nan_float}")
Examples of float()
for various string representations.
Handling Conversion Errors Gracefully
When parsing user input or external data, it's common for strings not to be perfectly formatted. Using try-except
blocks is the recommended Pythonic way to handle ValueError
exceptions that arise during type conversion, preventing your program from crashing.
def safe_int_conversion(s):
try:
return int(s)
except ValueError:
print(f"Warning: Could not convert '{s}' to an integer. Returning None.")
return None
def safe_float_conversion(s):
try:
return float(s)
except ValueError:
print(f"Warning: Could not convert '{s}' to a float. Returning None.")
return None
# Test cases
print(safe_int_conversion("100"))
print(safe_int_conversion("10.5"))
print(safe_int_conversion("hello"))
print(safe_float_conversion("3.14"))
print(safe_float_conversion("200"))
print(safe_float_conversion("not_a_number"))
Using try-except
for robust string-to-number conversion.
flowchart TD A[Start] --> B{Input String?} B -- Valid Integer --> C[int()] B -- Valid Float --> D[float()] B -- Invalid Format --> E[Try-Except Block] C --> F[Integer Result] D --> G[Float Result] E -- Catches ValueError --> H[Handle Error / Default Value] F --> I[End] G --> I[End] H --> I[End]
Decision flow for parsing strings to numbers in Python.
int(float("123.0"))
. Be aware that int(float("123.9"))
will truncate to 123
.Advanced Parsing with Regular Expressions (Optional)
For more complex parsing scenarios, such as extracting numbers from mixed strings or validating specific number formats, Python's re
module (regular expressions) can be very powerful. This allows you to pre-process the string to isolate the numerical part before attempting conversion.
import re
def extract_and_convert_int(text):
match = re.search(r'\d+', text) # Finds one or more digits
if match:
return int(match.group(0))
return None
def extract_and_convert_float(text):
# Finds optional sign, one or more digits, optional decimal and more digits
match = re.search(r'[-+]?\d*\.?\d+', text)
if match:
return float(match.group(0))
return None
print(f"Extracted int: {extract_and_convert_int('The answer is 42.')}")
print(f"Extracted float: {extract_and_convert_float('Price: $19.99')}")
print(f"Extracted float: {extract_and_convert_float('Temperature -5.5C')}")
Using regular expressions to extract and convert numbers from strings.