ValueError: could not convert string to float: 'X'
1 · The lesson
readWhat 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
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:
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.
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 ''.
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:
cell = "1,234.50" print(repr(cell)) # '1,234.50'
Remove separators and symbols before converting:
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:
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:
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:
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. Usepd.to_numeric(df["price"], errors="coerce")to turn bad values intoNaNinstead.
Related errors
- ValueError: invalid literal for int() with base 10: the same problem with
int(), which also refuses decimals like'3.5'. - TypeError: unsupported operand type(s) for +: 'int' and 'str': what happens when you forget to convert at all.
- TypeError: '<' not supported between instances of 'str' and 'int': comparing text from
input()with a number before converting it. - AttributeError: 'str' object has no attribute 'X': a number that is still text, found by a method call.
See Also
- All Python errors: the full index, by type and by when it happens.
- Input and output
- Numbers in depth
- CSV and JSON
- Exceptions (tutorial)
Found this useful? Share it with a friend who’s learning Python.