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:

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

Watch a course Python - The Practical Guide

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.

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.")