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

Better Stack Team
Updated on January 26, 2023

To parse a string to a float in Python, you can use the float() function. This function takes a string as input and returns a floating point number constructed from it. For example:

 
float('3.14') # returns float 3.14

To parse a string to an integer in Python, you can use the int() function. This function takes a string as input and returns an integer constructed from it. For example:

 
int('42') # returns integer 42

Note that these functions will raise a ValueError if the string cannot be parsed to the desired type.