How to Convert a String to Float or Int in Python?

Spread the love

Problem –

You want to convert a string to Float or int in python.

Solution –

Convert a string to Float in Python –

To convert a string to float in python, we can use the built-in float() function.

In [1]: float('100')
Out[1]: 100.0

In [2]: float('100.0')
Out[2]: 100.0

In [3]: float('100.25')
Out[3]: 100.25

Convert a string to Int in Python –

To convert a string to int in python, we can use the built-in int() function.

In [4]: int('100')
Out[4]: 100

If the string contains floating point values then doing this will throw an error.

In [5]: int('100.0')
Traceback (most recent call last):

  File "C:\Users\BHOLA\AppData\Local\Temp\ipykernel_13500\1958239749.py", line 1, in <cell line: 1>
    int('100.0')

ValueError: invalid literal for int() with base 10: '100.0'

To convert a string which contains floating point values, we need to first convert it to a float then into an int.

In [6]: int(float('100.0'))
Out[6]: 100

In [7]: int(float('100.25'))
Out[7]: 100

Rating: 1 out of 5.

Leave a Reply