Converting strings to floats in Python

This guide covers how to convert strings to floats in Python, including the different methods available and how they can be used.

Author: Jeremy Morgan
Published: December 9, 2023


In Python, it is common to encounter strings that need to be converted into floating-point numbers for mathematical operations or data analysis. In this article, we will explore how to convert a string to a float in Python, including the different methods available and their applications.

Float Function

There are several ways to convert a string to a float in Python. The most common method is to use the float() function, which takes a string as an argument and returns its floating-point equivalent.

For example:

my_string = "3.14"
my_float = float(my_string)
print(my_float) 

produces this output:

“How to convert a string to a float in Python”

It’s always best to throw some checking in there:

my_string = "3.14"
try:
    my_float = float(my_string)
    print(my_float)
except ValueError:
    print(f"Error: Unable to convert '{my_string}' to a float.")

That way if you ever get something that can’t be converted to a float:

“How to convert a string to a float in Python”

You can handle it gracefully:

“How to convert a string to a float in Python”

Eval Function

Another way to convert a string to a float is to use the eval() function, which evaluates an expression in a string and returns its result.

For example:

my_string = "3.14"
my_float = eval(my_string)
print(my_float) 

Produces identical output to float:

“How to convert a string to a float in Python”

Again it’s good practice to wrap this in some error handling:

my_string = "3.14"
try:
    my_float = eval(my_string)
    print(my_float)
except Exception as e:
    print(f"Error: Unable to evaluate '{my_string}' as a Python expression. {e}")

Note!!

The eval() function can be dangerous if used with untrusted input, as it can execute any Python code contained in the string. Therefore, it is recommended to use the float() function for converting strings to floats whenever possible.

Advanced Usage

In addition to converting a single string to a float, there are several other ways to convert multiple strings or even entire files of data into floating-point numbers in Python. Here are a few examples:

Converting Multiple Strings with map()

If you have a list of strings that need to be converted to floats, you can use the map() function to apply the float() function to each string in the list.

For example:

my_strings = ["3.14", "2.78", "1.65"]
my_floats = list(map(float, my_strings))
print(my_floats)

And here’s the output:

“How to convert a string to a float in Python”

This is a good way to convert multiple values. And again we should do some error checking:

my_strings = ["3.14", "2.78", "1.65"]

def convert_to_float(s):
    if not isinstance(s, str):
        raise ValueError(f"Expected string, got {type(s).__name__}")
    try:
        return float(s)
    except ValueError:
        raise ValueError(f"Unable to convert '{s}' to float")

try:
    my_floats = list(map(convert_to_float, my_strings))
    print(my_floats)
except ValueError as e:
    print(e)

By putting this in a method and doing some type checking we can make sure this is a safe way to convert the values.

Converting an Entire File of Data with numpy.loadtxt()

If you have a file containing data that needs to be converted to floats, you can use the numpy.loadtxt() function to read the file and convert its contents to floating-point numbers. \

For example:

import numpy as np
my_data = np.loadtxt("data.txt")
print(my_data)

Heres the output:

“How to convert a string to a float in Python”

and of course we want to get into good habits:

import numpy as np

def load_data(file_name):
    if not isinstance(file_name, str):
        raise ValueError(f"Expected string, got {type(file_name).__name__}")
    try:
        return np.loadtxt(file_name)
    except OSError:
        raise ValueError(f"Unable to load data from '{file_name}'")

try:
    my_data = load_data("data.txt")
    print(my_data)
except ValueError as e:
    print(e)

This is a great way to load a test file and convert the values. Something you’ll surely need to do at some point.

Conclusion

In this article, we covered the basics of converting strings to floats in Python, including the float() function and its use cases. We also explored more advanced usage of converting multiple strings or entire files of data into floating-point numbers using other methods such as map() and numpy.loadtxt(). These are several ways to attack the problem.

Remember don’t use Eval unless you have to.

Happy Coding!