ValueError: could not convert string to float in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
6 min

banner

# ValueError: could not convert string to float in Python

The Python "ValueError: could not convert string to float" occurs when we pass a string that contains characters or an empty string to the float() class.

To solve the error, remove all unnecessary characters from the string before calling float().

valueerror could not convert string to float

Here are 3 examples of how the error occurs.

main.py
# ⛔️ ValueError: could not convert string to float: '3.14%' print(float('3.14%')) # ⛔️ ValueError: could not convert string to float: '' print(float('')) # ⛔️ ValueError: print(float('abc3.14'))

common causes of the error

The string we are trying to convert to a floating-point number should not contain any characters or symbols.

# Things to note

To solve the error, make sure:

  • The string doesn't contain spaces or non-digit characters.
  • The string contains a period . as the decimal separator and not a comma ,.
  • The string is not empty.

# Using the re.findall() method to solve the error

One way to solve the error is to extract only the float value from the string using the re.findall() method.

main.py
import re my_str = 'a3.14b' m = re.findall(r'\d+\.\d+', my_str) print(m) # 👉️ ['3.14'] # ✅ Convert string to float my_float = float(m[0]) print(my_float) # 👉️ 3.14

using re findall

The re.findall method takes a pattern and a string as arguments and returns a list of strings containing all non-overlapping matches of the pattern in the string.

Make sure to print() the value you are passing to the float class as it may not contain what you expect.

# Using the str.replace() method to solve the error

An alternative approach is to use the str.replace() method to remove all unnecessary characters by replacing them with an empty string.

main.py
my_str = '1,2.345%' my_float = float(my_str.replace(',', '').replace('%', '')) print(my_float) # 👉️ 12.345

using replace to solve the error

We replaced the comma and the percent sign with an empty string and successfully converted the string to a floating-point number.

You can chain multiple calls to the replace() method to remove as many excess characters as necessary.

The str.replace method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.

main.py
my_str = '3.14%' result = float(my_str.replace('%', '')) print(result) # 👉️ 3.14

We only had to remove the percent sign from the string to be able to convert it to a floating-point number in the example.

# Floating-point numbers must have a period as the decimal point

Note that floating-point numbers must have a period as the decimal point and not a comma.

The following code sample causes the error.

main.py
my_str = '3,14' # ⛔️ ValueError: could not convert string to float: '3,14' my_float = float(my_str)

comma as decimal causes the error

To solve the error, replace the comma , with a period . to make the value a valid floating-point number.

main.py
my_str = '3,14' my_float = float(my_str.replace(',', '.')) print(my_float) # 👉️ 3.14 print(type(my_float)) # 👉️ <class 'float'>

replace comma with period

Once the comma , is replaced with a period ., the conversion to float works as expected.

# Using the str.strip() method to remove specific leading and trailing characters

You can also use the str.strip() method to remove specific leading and trailing characters.

main.py
my_str = '.%3.14%.' print(my_str) my_float = float(my_str.strip('%.')) print(my_float) # 👉️ 3.14

using strip to solve the error

The str.strip() method returns a copy of the string with the leading and trailing characters removed.

Characters are removed from the leading and trailing ends until reaching a character that is not contained in the set of specified characters we passed to the method.

Note that the str.strip() method only removes the specified leading and trailing characters from the string.

# Using a try/except block to handle the error

You can also use a try/except block to handle the error.

main.py
my_str = ' ' try: result = float(my_str) except ValueError: result = 0 print(result) # 👉️ 0

using try except statement

If calling the float() class with the value raises a ValueError, the except block runs where we set the result variable to 0.

You can also use the str.replace() method to remove excess characters in the except block.

main.py
my_str = '12.345%' try: my_float = float(my_str) except ValueError: my_float = float(my_str.replace('%', '')) print(my_float) # 👉️ 12.345 print(type(my_float)) # 👉️ <class 'float'>

# Taking float values from user input

If you get the error when taking floating-point numbers from user input, use a try/except statement to handle the error.

main.py
try: num_1 = float(input('Enter a float: ')) num_2 = float(input('Enter another float: ')) result = num_1 + num_2 print(result) except ValueError: print('Invalid float value supplied.')

taking float point numbers from input

If the user enters an invalid floating-point number, a ValueError is raised and is then handled by the except block.

The error is handled, so the program never crashes.

I have a detailed guide on how to take float user input in Python.

# Make sure to not pass an empty string to the float() class

Make sure you aren't passing an empty string or a string that contains a space to the float() class.

main.py
my_str = ' ' result = float(my_str.strip() or 0) print(result) # 👉️ 0.0

We used the strip() method without passing it any arguments to remove any trailing and leading whitespace.

If removing all leading and trailing whitespace from the string returns an empty string, we pass 0 to the float() class.

Alternatively, you can use an if/else statement to check if the string is empty before passing it to float().

main.py
my_str = ' ' if my_str.strip(): my_int = float(my_str) else: # 👇️ This runs print('The specified string is empty')

The string in the example contains only spaces, so it doesn't pass the test in the if statement and the float() class is never called.

# If your string contains spaces, remove them

If your string contains a valid floating-point number but also contains spaces, remove the spaces.

main.py
# ✅ Remove only leading and trailing whitespace my_str = ' 3.14 ' my_float = float(my_str.strip()) print(my_float) # 👉️ 3.14

The code sample uses the str.strip() method to remove only the leading and trailing whitespace.

Use the str.replace() method if you need to remove all spaces from the string.

main.py
my_str = ' 3 . 1 4 ' my_float = float(my_str.replace(' ', '')) print(my_float) # 👉️ 3.14

We remove all spaces by replacing each with an empty string.

# Solving the error when reading from files

If you got the error when reading from a file, a line in the file likely doesn't contain a floating-point number.

Assuming you have the following example.txt file.

shell
1.23 4.56 abc 6.78

Here is an example of how the error is raised.

main.py
with open('example.txt', 'r', encoding="utf-8") as f: lines = f.readlines() for line in lines: try: a_float = float(line) print(a_float) except ValueError: print('Invalid float:', line)

reading from a file

The third line in the file contains non-digit characters.

Trying to convert the value to a floating-point number causes the error.

You can use a try/except statement to handle the error as shown in the example.

The line might also contain spaces, which is also not allowed.

You can use the str.replace() method to remove the spaces from the string.

main.py
# ✅ Remove only leading and trailing whitespace my_str = ' 3.14 ' my_float = float(my_str.strip()) print(my_float) # 👉️ 3.14 # -------------------------------------------------- # ✅ Remove all spaces my_str = ' 3 . 1 4 ' my_float = float(my_str.replace(' ', '')) print(my_float) # 👉️ 3.14

# Solve the error when using pandas

If you got the error when using pandas, your DataFrame likely contains invalid floating-point numbers, e.g. ones where the decimal separator is a comma , instead of a period.

Here is an example of using the str.replace() method to replace each comma with a period before converting to float.

main.py
import pandas as pd df = pd.DataFrame({ 'employee': ['Alice', 'Bobby', 'Carl'], 'salary': ['12,34', '23,45', '34,56'] # 👈️ comma as decimal (BAD) }) df['salary'] = [ float( str(value).replace(',', '.') # 👈️ period as decimal ) for value in df['salary'] ] # employee salary # 0 Alice 12.34 # 1 Bobby 23.45 # 2 Carl 34.56 print(df)

We used a list comprehension to iterate over the salary values.

On each iteration, we replace the comma , with a period . before converting to float.

You can also use the str.replace() method if the values contain a character that has to be removed, e.g. a dollar sign or a percent sign.

main.py
import pandas as pd df = pd.DataFrame({ 'employee': ['Alice', 'Bobby', 'Carl'], 'salary': ['12.34%', '23.45%', '34.56%'] # 👈️ has percent % }) df['salary'] = [ float( str(value).replace('%', '') # 👈️ remove percent sign ) for value in df['salary'] ] # employee salary # 0 Alice 12.34 # 1 Bobby 23.45 # 2 Carl 34.56 print(df)

This time, we used the str.replace() method to remove the percent % signs from the string before converting to float.

# Things to note when solving the error

To solve the "ValueError: could not convert string to float" error, make sure:

  • The string doesn't contain spaces or non-digit characters.
  • The string contains a period . as the decimal separator and not a comma ,.
  • The string is not empty.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.