In Python, we can only convert specific string values to float. If we try to convert an invalid string to a float, we will raise the ValueError: could not convert string to float.

To solve this error, ensure you strip the string of invalid characters like commas, spaces or brackets before passing it to the float() function.

This tutorial will go through how to solve the error with the help of code examples.


ValueError: could not convert string to float 

In Python, a value is information stored within a particular object. You will encounter a ValueError in Python when you use a built-in operation or function that receives an argument with the right type but an inappropriate value.

A string is a suitable type to convert to a float. But several string values are not suitable to convert to float:

  • A value that contains non-special terms, for example, ‘nan’ is a special term, “bread” is not.
  • A value that contains a commas, speech marks and other non alphanumeric characters.
  • A value that contains spaces.

We can convert inf and nan to floats because they represent specific floats in Python, namely infinity and NaN (Not a Number).

Example

Consider the following CSV file called money.csv that contains the epoch timestamp and money in two accounts.

"'1645916759'",20000,18000
"'1645916790'",21000,17000
"'1645916816'",20500,17250

Next, we will write a program that will read the information from the CSV file and print it to the console. We will import the csv library to read the CSV file. Let’s look at the code:

from datetime import datetime

with open("money.csv", "r") as money:

   readf = csv.reader(money)

   for line in readf:

       time = float(line[0])

       account_one = float(line[1])

       account_two = float(line[2])

       print(f'At date: {datetime.fromtimestamp(time)}, Account one value £{account_one}, Account two value £{account_two}')

We use the datetime library to convert the epoch timestamp to a date. Let’s run the code to see the result:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
      2     readf = csv.reader(money)
      3     for line in readf:
----≻ 4         time = float(line[0])
      5         account_one = float(line[1])
      6         account_two = float(line[2])
ValueError: could not convert string to float: "'1645916759'"

The error occurs because the epoch timestamp contains inverted commas, which are invalid string values to convert to a float.

Solution

We need to strip the epoch timestamp of the inverted commas using the String strip() method to solve this error. Let’s look at the revised code:

from datetime import datetime

with open("money.csv", "r") as money:

   readf = csv.reader(money)

   for line in readf:

       time = float(line[0].strip("'"))

       account_one = float(line[1])

       account_two = float(line[2])

       print(f'At date: {datetime.fromtimestamp(time)}, Account one value £{account_one}, Account two value £{account_two}')

Let’s run the code to see the result:

At date: 2022-02-26 23:05:59, Account one value £20000.0, Account two value £18000.0
At date: 2022-02-26 23:06:30, Account one value £21000.0, Account two value £17000.0
At date: 2022-02-26 23:06:56, Account one value £20500.0, Account two value £17250.0

The code successfully prints each line in the money.csv file.

Example #2

Let’s look at an example, where we write a program that converts a weight from kilograms to pounds. First, we will ask a user to insert the weight in kilograms that they want to convert to pounds:

weight = float(input("Enter the weight to convert to pounds: "))

Next, we will define the conversion value to convert kilograms to pounds:

convert_to_lbs = 2.205

Then, we will attempt to convert the kilogram value to pounds and print the result to the console.

weight_in_lbs = weight * convert_to_lbs

print(f'{weight}kg is {weight_in_lbs}lbs')

Let’s run the code to see what happens:

Enter the weight to convert to pounds: 87,50
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
----≻ 1 weight = float(input("Enter the weight to convert to pounds: "))
ValueError: could not convert string to float: '87,50'

We raise the ValueError because the string we input contains a comma.

Solution

To solve the error we can use a try-except block. The program will try to run the code in the “try” block, if unsuccessful, the program will run the code in the “except” block. Let’s look at the revised code:

convert_to_lbs = 2.205

try: 

    weight = float(input("Enter the weight to convert to pounds: "))

    weight_in_lbs = weight * convert_to_lbs

    print(f'{weight}kg is {round(weight_in_lbs,1)}lbs')

except:

    print('Please insert a valid weight. The weight cannot contain commas, spaces or special characters')

Let’s try the code and input an invalid string:

Enter the weight to convert to pounds: 87,50
Please insert a valid weight. The weight cannot contain commas, spaces or special characters

We see that the program executes the print statement in the except block. Let’s run the code and input a valid string:

Enter the weight to convert to pounds: 87.50
87.5kg is 192.9lbs

The code successfully executes the code in the try block and prints the kilogram and the converted pound value to the console.

Summary

Congratulations on reading to the end of this tutorial! The error ValueError: could not convert string to float occurs if you try to convert a string to a float that contains invalid characters. To solve this error, check the string for characters that you can remove and use the strip() method to get rid of them. If a value has a comma instead of a decimal point, you can use replace() to replace the comma.

You can also use a try-except statement to catch the ValueError and pass. This method is useful if you are taking input from a user.

For further reading on ValueErrors, go to the article: How to Solve Python ValueError: list.remove(x) x not in list

For further reading on converting values, go to the article: How to Solve Python TypeError: int() argument must be a string, a bytes-like object or a number, not ‘list’

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!