In this tutorial, we will see how to convert String to float in python.
You can simply use float() function to convert String to float.
Let’s understand with the help of a simple example.
1 2 3 4 5 6 7 |
str="22.4543232" f=float(str) print("Type of f:",type(f)) print(f) |
Output:
Type of f:
22.4543232
22.4543232
What happens if String cannot be converted to float
If String cannot be converted to float then it will raise ValueError.
Let’s understand with the help of example.
1 2 3 4 5 |
str="abc" f=float(str) print(f) |
Output:
—————————————————————————
ValueError Traceback (most recent call last)
in ()
1 str=”abc”
—-> 2 f=float(str)
3 print(f)
ValueError Traceback (most recent call last)
1 str=”abc”
—-> 2 f=float(str)
3 print(f)
ValueError: could not convert string to float: ‘abc’
That’s all about converting Python String to float.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.