Could not convert string to float in Python

In this Python tutorial, I will show you what is ValueError: could not convert string to float in Python. And, also to handle this error using different methods with examples.

ValueError in Python

In Python, a ValueError is a type of Exception that typically indicates that a function received an argument of the right type but inappropriate value. For instance, We may encounter a ValueError: could not convert to string to float in Python, if we attempt to convert a string to a float, and the string is not a valid representation of a float like:

temperature = "96.5 C"

print(float(temperature))

The output will be:

Traceback (most recent call last):
  File "C:\Users\USER\PycharmProjects\pythonProject\TS\main.py", line 3, in <module>
    print(float(temperature))
          ^^^^^^^^^^^^^^^^^^
ValueError: could not convert string to float: '96.5 C'
valueerror could not convert string to float in Python

As the string(Temperature) contains a non-numeric data type in it. The float() in Python could not be able to convert that and will cause us an error.

How to Handle this ValueError: could not convert string to float in Python

There are many different ways in Python to handle this ‘could not convert string to float:‘ issue:

  • Data cleaning or preprocessing
  • Using try/except blocks
  • Using conditional checks
READ:  Sum All the Items in Python List Without using sum()

Let’s see them one by one using illustrative examples.

Method-1: Handle ValueError could not convert string to float in Python using data cleaning or preprocessing

Always ensure that the data we are trying to convert to a Python float represents a numerical value. We may need to preprocess our data to clean it and ensure it is in the right format.

For example, consider a dataset in Python of prices of various items in a US grocery store. The price values may be stored as strings with a dollar sign, e.g., “$5.00”. If we try to convert this directly to a Python float, we will get a ValueError because of the dollar sign. To handle this, we could remove the dollar sign before conversion:

price_string = "$5.0"
price_string = price_string.replace("$", "")
price_float = float(price_string)
print(price_float)

The output is: The replace() method will replace the dollar ‘$’ sign from the string with an empty argument(as provided) and we can easily convert the Python string value to Python float value.

5.0
valueerror could not convert string to float in Python with replace()

Note: we can use strip() and lstrip() from string methods in Python to remove the ‘$’ dollar sign from the string. As they can also remove characters from a string.

This way we can handle the ValueError: could not convert string to float: by data cleaning or preprocessing.

Method-2: Use try/except blocks to handle ValueError: could not convert string to float: ” In Python

In Python, the try block contains the block of code that may cause an error and if any error occurs then the except block will handle the error and will do so according to the instruction provided.

READ:  How to Create String with Single Quotes in Python

For instance, let’s consider a simple example where we have a list of strings in Python, each representing the elevation in feet of different landmarks in the United States. Some of these are numerical, while others are non-numerical due to data errors or unknown values.

In this code, we iterate over the elevations Python list. For each item, we try to convert the string to a float. If the Python string represents a number (like “14000”), the conversion is successful, and the float value replaces the original Python string in the list.

However, if the string doesn’t represent a valid numerical value (like “Unknown” or “Not Available”), the conversion raises a ValueError in Python. In the except block, we catch this error, print an error message, and continue to the next item, leaving the original string in place.

elevations = ["14000", "Unknown", "12000", "Not Available", "10000", "16000"]

for i in range(len(elevations)):
    try:
        # Try to convert the string to a float
        elevations[i] = float(elevations[i])
    except ValueError:
        # If ValueError occurs, print an error message and keep the original string
        print(f"Cannot convert {elevations[i]} to a float. Keeping the original string.")
        continue

print(elevations)

The output is: After looping through all items in the Python list, we print the list. Now, it contains floats for all valid elevations and the original strings for all entries that couldn’t be converted to a Python float.

Cannot convert Unknown to a float. Keeping the original string.
Cannot convert Not Available to a float. Keeping the original string.
[14000.0, 'Unknown', 12000.0, 'Not Available', 10000.0, 16000.0]
could not convert string to float Python using try except block

This way we can easily handle the exception (ValueError: could not convert string to float) in Python using try/except blocks.

READ:  How to check if a variable is a number in Python?

Method-3: Handle ValueError: could not convert string to float: in Python with conditional statements

Another option is to only attempt to convert a string to a float in Python if it is actually a numerical value. We can write a function that checks if a string is a number before attempting conversion:

For example, we have to write down the prices of the products available on an eCommerce website, But some of the product prices are not available, and we want to do some mathematical calculations with the prices available:

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

prices = ["$5.0", "$10.0", "Not available"]

for price in prices:
    price = price.replace("$", "")
    if is_number(price):
        price = float(price)
        print(price)
    else:
        continue

The output is:

5.0
10.0
Python ValueError could not convert string to float in Python using conditional statements

This way we can use conditional statements to resolve ValueError: could not convert string to float Python

Conclusion

Understanding the cause and resolution for the ValueError: could not convert string to float in Python error is vital for any Python developer. We have seen what could not convert string to float in Python error and how to handle this with demonstrative examples using different methods like try/except blocks, conditional statements, etc.

You may like the following Python tutorials: