Sign In
Sign In

How to Convert String to Float in Python

How to Convert String to Float in Python
Amr Essam
Technical writer
Python
02.10.2024
Reading time: 7 min

Python variables provide an easy way to store and access data in a program. They represent the memory addresses that contain the required data values. Each variable has a specific data type which reflects the kind of data it can store like an int, float, or a string.

In some scenarios, we might need to convert one data type to another in order to be used in a later operation in our program. For example, if we receive an integer number from a user like this x = input(“Please enter a number:”) this input variable will be automatically stored as a string. So, if we’re to do a numeric operation on it we’ll need to convert it to an int first.

This process of converting between data types is called type casting or type conversion. It is a fundamental concept in programming that offers compatibility and flexibility in our programs.

In this article, we will cover a common example of type casting in Python which is converting a string to a float. We will also look at handling conversion errors that might appear in some scenarios.

Type Casting Categories

There are mainly two kinds of type casting, explicit casting and implicit casting.

Explicit Casting

In the explicit casting the developer manually declares the conversion and writes it inside the code. This is usually done by using a conversion function for a specific data type.

For example, we can convert a float to an int with the following code:

x=1.5  # float variable
y=int(x) # convert to integer with the int() function

To determine the data type of y we can use the type() function as follows:

print(type(y))

Now the output should print the type of y as int

Image8

The explicit casting gives the programmer control over when and how to execute the conversion.

Implicit Casting

In the implicit casting the interpreter automatically converts between data types without the need for the developer to declare it in the code. This is usually done to allow for compatibility in an operation and prevent data loss.

For example, when performing addition operation between a float and an int as follows:

x=1.5
y=1
z= x+y

In the above example, Python will automatically convert the integer value 1 to a float:

print(type(z))
print(z)

Now the output should print the type of z and its value:

Image3

As we can see from the image, the variable z which is the result of the addition has a data type of float.

Converting Strings to Floats Using float() function

To convert a string to a float in Python we use a function called float(). It is a built-in function that takes an argument (whether a string or an int) and constructs a floating-point number from it.

For example, the following code will convert the value of the my_string variable to a float:

my_string="10.267"
my_float=float(my_string)

We can then check the type and value of the my_float variable with the following code:

print(type(my_float))
print(my_float)

Now if we run the above example we’ll get the type of my_float variable as a float with the same value constructed from the converted string:

Image6

By converting the string to a float we can now execute the numeric operations we need on the converted variable:

Image2

In the above image we performed an addition operation on our variable (my_float+10) and it was executed successfully.

When we use the float() function, what happens under the hood is that it calls an object method named __float__(). This __float__() method implements the float() function and executes the logic for the conversion. In other words, when we write float(x) it is translated into x.__float__().

Handling Conversion Errors with try/except

We might encounter a scenario where a string value isn’t applicable for conversion to a float. For example, if the user inputs a string that doesn’t match a valid float number format (contains letters, special characters, etc).

To handle such cases, we need to implement a validation logic that checks if the input is applicable for conversion. A common implementation for this logic can be done using the Python try/except block.

First let’s test the scenario without error handling using the following code:

invalid_string="abc10.5"
my_float=float(invalid_string)

Now let’s try to run our code:

Image7

As we can see in the above image, the code produced a ValueError because the invalid_string variable contained an improper float value format.

To handle such error, we can use a try/except block as follows:

invalid_string="abc10.5"
try:
    my_float=float(invalid_string)
except ValueError:
    print("Please enter a valid string value")

In the above code we are executing our conversion inside the try block, then we’re using the except block to check if the conversion throws a ValueError exception.

Let’s run our code again:

Image9

As we can see in the above image, because this conversion throws a ValueError the code inside the except block gets executed and prints our output message.

Converting Lists of Strings to Floats

We can also apply the type casting process to a list of objects instead of a single variable. In that case we’ll be converting each item in the list to a different data type. So, we can extend upon our previous example and convert a list of strings to floats.

Let’s explore a couple of ways in which we can achieve this:

Using List Comprehension

List comprehension is a very handy way to create a new list out of an existing list in Python. It provides a simpler and shorter syntax in which you can apply specific logic or operations on the existing list items to produce the new list.

We can convert a list of strings to floats using list comprehension with the following code:

string_list=["10.1", "10.2", "10.3", "10.4"]
float_list=[float(item) for item in string_list]

In the above code, we create the float_list from the string_list by iterating over each item in the string_list and executing the float() function.

We can then print the new float_list and the type of each item inside it with the following code:

print(float_list)
for x in float_list:
    print(type(x))

Now let’s run our code and check the output:

Image5

As we can see in the above image, the float_list was populated by the items from the string_list, but the type of each item was converted to a float.

Using the map() function

Another way for converting a list of strings to floats is by using the map() function. The map() function returns a map object after taking two arguments, the first is a function that we want to execute, and the second is an iterable (list, tuple, etc) where we want to execute the first function on each item.

Let’s explain this on our scenario using the following code:

string_list=["10.1", "10.2", "10.3", "10.4"]
float_list=list(map(float, string_list))

Again we’ve our existing string_list and we want to create a new float_list from it after conversion. The map() function here is taking two arguments which are float and string_list. This means we want to apply the float() function on each item in the string_list.

Since the map() function returns a map object, we’re passing it to the list() function to convert the return object into a list which will be stored in the float_list object.

Let’s run our code and check the output:

Image4

We can see the float_list is again created from the string_list by converting the string items to floats.

Using Traditional for loop

We can also convert our list of strings to floats using our good friend, the Python for loop as follows: 

string_list=["10.1", "10.2", "10.3", "10.4"]
float_list=[]
for item in string_list:
    float_list.append(float(item))

In the above code, we iterate over the string_list and append each item into the float_list after converting it to a float.

Now let’s run our code:

Image1

Again we’ve our float_list here is populated from the string_list and the items are converted from strings to floats.

Conclusion

Python type casting is a fundamental concept that involves converting one data type to another. It provides compatibility and flexibility for programmers in their code. In this article we’ve covered a common example of type casting which is converting a string to a float using the float() function. We also used the try/except block to handle conversion errors when the input string format is not valid.

Python
02.10.2024
Reading time: 7 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us
Hostman's Support