Last updated: Apr 8, 2024
Reading time·6 min
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()
.
Here are 3 examples of how the error occurs.
# ⛔️ 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'))
The string we are trying to convert to a floating-point number should not contain any characters or symbols.
To solve the error, make sure:
.
as the decimal separator and not a comma ,
.re.findall()
method to solve the errorOne way to solve the error is to extract only the float value from the string
using the re.findall()
method.
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
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.
print()
the value you are passing to the float
class as it may not contain what you expect.str.replace()
method to solve the errorAn alternative approach is to use the str.replace()
method to
remove all unnecessary characters
by replacing them with an empty string.
my_str = '1,2.345%' my_float = float(my_str.replace(',', '').replace('%', '')) print(my_float) # 👉️ 12.345
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.
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.
Note that floating-point numbers must have a period as the decimal point and not a comma.
The following code sample causes the error.
my_str = '3,14' # ⛔️ ValueError: could not convert string to float: '3,14' my_float = float(my_str)
To solve the error, replace the comma ,
with a period .
to
make the value a valid floating-point number.
my_str = '3,14' my_float = float(my_str.replace(',', '.')) print(my_float) # 👉️ 3.14 print(type(my_float)) # 👉️ <class 'float'>
Once the comma ,
is replaced with a period .
, the conversion to float works
as expected.
str.strip()
method to remove specific leading and trailing charactersYou can also use the str.strip()
method to remove specific leading and
trailing characters.
my_str = '.%3.14%.' print(my_str) my_float = float(my_str.strip('%.')) print(my_float) # 👉️ 3.14
The str.strip() method returns a copy of the string with the leading and trailing characters removed.
Note that the str.strip()
method only removes the specified leading and
trailing characters from the string.
try/except
block to handle the errorYou can also use a try/except block to handle the error.
my_str = ' ' try: result = float(my_str) except ValueError: result = 0 print(result) # 👉️ 0
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.
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'>
If you get the error when taking floating-point numbers from user input, use a
try/except
statement to handle the error.
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.')
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 you aren't passing an empty string or a string that contains a space
to the float()
class.
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()
.
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 a valid floating-point number but also contains spaces, remove the spaces.
# ✅ 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.
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.
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.
1.23 4.56 abc 6.78
Here is an example of how the error is raised.
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)
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.
# ✅ 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
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.
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.
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.
To solve the "ValueError: could not convert string to float" error, make sure:
.
as the decimal separator and not a comma ,
.You can learn more about the related topics by checking out the following tutorials: