Skip to content

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

To parse a string to a float or int in Python, you can use the float() and int() functions, respectively.

Here's an example of how you can use these functions:

Parse a string to a float or integer using float and int functions in Python

python
string = "1.23"

# Parse the string to a float
float_value = float(string)
print(float_value)  # Output: 1.23

# Parse the string to an int
int_value = int(float_value)
print(int_value)  # Output: 1

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

Note that the int() function will truncate the decimal part of the float value when converting it to an integer.

If the string cannot be parsed to the desired type (e.g. it contains characters that are not digits), the functions will raise a ValueError exception. You can use a try-except block to handle this exception.

Handling ValueError raised byfloat and int functions in Python

python
string = "abc"

try:
    float_value = float(string)
except ValueError:
    print("Could not parse string to float.")

try:
    int_value = int(string)
except ValueError:
    print("Could not parse string to int.")

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.