Convert string to float in python :
Sometimes, we need to convert a string to a float value. For example, if you are receiving float data in string format from the server and if you want to do any arithmetic operations on them, you need to convert them to float first.
For example, let’s take a look at the below program :
a = "11.34" b = 11.4 print(a+b)
If we try to run it, it will throw one error like :
Traceback (most recent call last): File "example.py", line 4, in print(a+b) TypeError: must be str, not float
So, we need to convert the string to a float before using it with any arithmetic operations. In this tutorial, we will learn how to convert a string to a float in python.
Simple program to convert a string to float :
Let’s try to change the above example and convert the string to a float before doing the addition.
float(str) is used to convert a string to a float in python.
a = "11.34" b = 11.4 print(float(a)+b)
It will print :
Converting all items in a list :
Suppose we have one list with float numbers stored as a string. If our problem is to find out the sum of all of these numbers, we need to convert them to float before doing the addition operation.
We can use one for loop to iterate over the list.
num_list = ["1.11","2.22","3.33"] sum = 0 for x in num_list : sum += float(x) print(sum)
It will print 6.66 as output.
We can also convert these elements and create one list of floating values like below :
num_list = ["1.11","2.22","3.33"] float_list = [ float(x) for x in num_list] print(num_list) print(float_list)
The output will be :
['1.11', '2.22', '3.33'] [1.11, 2.22, 3.33]
As you can see that the original list with string values are converted to a list with floating values.
In this tutorial, we have learned how to convert a string value to float. If we are not sure about the receiving values, it is a good coding practice to convert it before using.
Try to run the examples and drop one comment below if you have any queries.
You might also like :
- Python Common String methods
- Python program to sort words of a string in alphabetical order
- Python 3 program to check if a string is pangram or not
- Python 3 program to count the total number of characters in a string
- Find total number of lowercase characters in a string using Python 3
- Python program to remove characters from odd or even index of a string