Editor

ValueError: could not convert string to float

What it means

float() was given text it cannot read as a number. It understands '3.14', '-2' and '1e3', but not words, thousands separators like '1,250', or symbols like $ and %. The text after the colon shows exactly what it received.

1. A placeholder word instead of a number

This raises the error

Broken
readings = ['21.5', '22.0', 'N/A', '23.1']
values = [float(r) for r in readings]
print(sum(values))
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
ValueError: could not convert string to float: 'N/A'

The fix

Fixed
readings = ['21.5', '22.0', 'N/A', '23.1']
values = []
for r in readings:
try:
values.append(float(r))
except ValueError:
print('skipping', repr(r))
print(sum(values))
Output
skipping 'N/A'
66.6

Missing data often shows up as 'N/A', '-' or an empty string. Catching ValueError lets you skip or replace those values instead of crashing.

Try fixing it yourself in the editor

2. Commas used as thousands separators

This raises the error

Broken
salary = '1,250.50'
print(float(salary))
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
ValueError: could not convert string to float: '1,250.50'

The fix

Fixed
salary = '1,250.50'
print(float(salary.replace(',', '')))
Output
1250.5

Python numbers never contain commas, so remove them first. If the comma is a decimal mark, as in '3,5', replace it with a dot instead.

Try fixing it yourself in the editor

3. A currency sign or percent sign in the text

This raises the error

Broken
price = '$19.99'
tax = float(price) * 0.08
print(tax)
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
ValueError: could not convert string to float: '$19.99'

The fix

Fixed
price = '$19.99'
tax = float(price.strip('$')) * 0.08
print(round(tax, 2))
discount = '15%'
print(float(discount.rstrip('%')) / 100)
Output
1.6
0.15

strip('$') and rstrip('%') remove the symbols from the ends, leaving text that float() can read.

Try fixing it yourself in the editor

When you see this error, check

  • Print repr(value) to see hidden spaces, symbols or an empty string.
  • Remove commas, currency signs and units before converting.
  • Look out for empty strings from blank lines or empty cells.
  • Wrap conversions of file or web data in try / except ValueError.

All Python errors · How to read a traceback · Step through your code