ValueError
ValueError: could not convert string to float: 'abc'
Traceback
Traceback (most recent call last):
File "main.py", line 1, in <module>
price = float("$19.99")
ValueError: could not convert string to float: 'abc'What causes this error
A string passed to float() does not represent a valid floating-point number. The string contains non-numeric characters, multiple decimal points, or locale-specific formatting.
How to fix it
Validate strings before conversion with try/except ValueError. Strip whitespace and currency symbols. Handle locale-specific formats. Use pandas for robust parsing of data files with inconsistent formats.
Code that causes this error
price = float("$19.99")Fixed code
raw = "$19.99"
cleaned = raw.replace("$", "").replace(",", "")
try:
price = float(cleaned)
except ValueError:
price = 0.0About ValueError
This ValueError occurs when `float()` receives a string that does not represent a valid floating-point number. Valid float strings include '3.14', '-2.5', '1e10', 'inf', '-inf', and 'nan'. Invalid strings include words, strings with multiple decimal points, strings with currency symbols or commas, and empty strings.
This error commonly appears in data processing when reading CSV files with missing or malformed numeric data, when parsing user input, and when processing locale-specific number formats that use commas as decimal separators. The `locale` module can help parse locale-formatted numbers, and libraries like `pandas` have robust parsing that handles various number formats and missing values automatically.
Common scenarios
Converting user input strings to numbers without validation
Unpacking iterables with an unexpected number of elements
Passing out-of-range values to mathematical functions
Processing data files with inconsistent or malformed records