PythonMastery
reference 3 min read · lesson 63 of 80 in Errors

ValueError: could not convert string to float: 'X'

1 · The lesson

read

What this error means

You called float() on text that isn't a plain number. float() reads digits, one decimal point, an optional + or - sign and an optional exponent like 1e3. It also ignores spaces and newlines at the start and the end. Anything else in the text, like a comma, a currency sign or a percent sign, makes it fail. The end of the message shows the exact text it got, inside quotes, and that is the most useful part: look at it closely.

When you see it

python
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    total = float(price) * 2
            ~~~~~^^^^^^^
ValueError: could not convert string to float: '$5.99'

When the quotes at the end are empty, the text was empty:

python
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    value = float(cell)
ValueError: could not convert string to float: ''

Why it happens

Four situations cause almost every case.

1. Commas as thousands separators. People and spreadsheets write 1,234.50. float() does not accept the comma.

python
amount = float("1,234.50")    # ValueError: '1,234.50'

Some countries write the decimal point as a comma, like 3,75. That fails for the same reason.

2. Symbols around the number. Currency signs ($5.99, €20), percent signs (45%) and units (12kg) are not part of a number.

3. An empty value. An empty cell in a CSV file, a blank line at the end of a file, or a reader who pressed Enter without typing anything all give you ''.

python
row = ["Ada", "", "36"]
height = float(row[1])        # ValueError: ''

4. Words where you expected a number. A header row read as data ('price'), a placeholder like 'N/A' or '-', or a reader who typed ten instead of 10.

How to fix it

Look at the exact text first. Print it with repr(). Quotes show where the text starts and ends:

python
cell = "1,234.50"
print(repr(cell))             # '1,234.50'

Remove separators and symbols before converting:

python
price = "$1,234.50"
clean = price.replace("$", "").replace(",", "")
print(float(clean))           # 1234.5

percent = "45%"
print(float(percent.rstrip("%")) / 100)   # 0.45

If the decimal point is a comma, as in 3,75, replace it with a dot: float("3,75".replace(",", ".")) gives 3.75. Only do this when you know which format the data uses, because 1,234 means one thousand in one format and a little more than one in the other.

Handle empty values on purpose. Decide what an empty cell means, then write that down in the code:

python
cells = ["12.5", "", "7"]
values = [float(c) for c in cells if c.strip()]
print(values)                 # [12.5, 7.0]

Catch the error when the text comes from a person. Ask again instead of crashing:

python
def to_number(text):
    try:
        return float(text)
    except ValueError:
        return None

print(to_number("3.5"))       # 3.5
print(to_number("ten"))       # None

With input(), put the try inside a loop and ask until you get a number.

Skip the header row of a CSV. csv.DictReader uses the first row as column names, so you never convert the header by mistake:

python
import csv
import io

data = io.StringIO("item,price\nkeyboard,49.99\nmouse,19.50\n")
total = sum(float(row["price"]) for row in csv.DictReader(data))
print(f"{total:.2f}")         # 69.49

Spaces and newlines are fine. float(" 3.0 ") and float("12.5\n") both work, so you don't need .strip() just for them.

When you'd see this in real code

  • A CSV exported from Excel or Google Sheets, where money columns are formatted as $1,234.50.
  • Data scraped from a web page, where a price is "€ 20" or a number has a non-breaking space inside it.
  • A file with a header row, read with csv.reader, where the first row is ['item', 'price'].
  • A sensor or log file where missing readings are written as N/A, - or an empty field.
  • In pandas, df["price"].astype(float) fails with the same message. Use pd.to_numeric(df["price"], errors="coerce") to turn bad values into NaN instead.

See Also

Found this useful? Share it with a friend who’s learning Python.