Fix "ValueError: invalid literal for int() with base 10" in Python
ValueError: invalid literal for int() with base 10: 'abc'
- ValueError: invalid literal for int() with base 10: ''
- ValueError: invalid literal for int() with base 10: '3.5'
- ValueError: invalid literal for int() with base 10: '1,234'
- ValueError: could not convert string to float: '1,5'
- ValueError: Unable to parse string "N/A" at position 3
int() received a string that is not a whole number: text, an empty string '', a decimal '3.5' or a thousands separator '1,234'. Look at the quoted value at the end of the message, then clean or validate the data before converting: try/except ValueError, int(float(s)) for a decimal, .replace() for separators.
What this error means
Called on a string, int() only accepts digits of the requested base (10 by default), an optional + or - sign, surrounding whitespace and _ between digits. Anything else raises ValueError, with the received value shown by repr(): '' means an empty string, '3.5' a decimal number, '12 €' an extra symbol. int() does not convert a decimal string, while int(3.5) on a float works and truncates. float() raises "could not convert string to float" instead, and pandas shows the same messages with astype(), or "Unable to parse string" with pd.to_numeric().
Common causes
- Unvalidated user input:
int(input())when the user types text or just presses Enter (empty string''). - Decimal number as text:
int('3.5')always fails, even though the value looks like a number. - Regional format or unit: thousands separators (
'1,234','1 234'), decimal comma ('1,5'), currency symbol or percentage ('12€','45%'). - Dirty CSV or Excel file: empty cells,
'N/A','-', or a header row processed as data (int('age')). - Wrong split:
line.split(',')[0]returning the name instead of the id, or a separator different from the file’s one.
Step-by-step fix
-
Read the value shown in the message
The end of the message shows exactly what
int()received. If needed, print it withrepr()right before the conversion to see spaces, invisible characters and the type.print(repr(value), type(value)) -
Validate input with
try/exceptFor user input, try the conversion and ask again on error. It is more reliable than
str.isdigit(), which rejects'-3'but accepts some characters such as'²'.while True: raw = input("Age: ").strip() try: age = int(raw) break except ValueError: print(f"{raw!r} is not a whole number, try again.") -
Convert a decimal string
Go through
float()then choose explicitly: truncate withint(), round withround()(round half to even:round(2.5)is2), or keep exact precision withDecimalfor amounts.from decimal import Decimal value = "3.5" truncated = int(float(value)) # 3 rounded = round(float(value)) # 4 exact = Decimal(value) # Decimal('3.5') -
Clean regional formats
Remove spaces (non-breaking ones included), symbols and thousands separators before converting. Adapt to the source format: in French the comma is the decimal mark; in English it separates thousands.
def parse_fr(text: str) -> float: cleaned = text.strip() for junk in (" ", " ", " ", "€", "%"): cleaned = cleaned.replace(junk, "") return float(cleaned.replace(",", ".")) def parse_en(text: str) -> float: return float(text.strip().replace(",", "").replace("$", "")) print(parse_fr("1 234,5 €")) # 1234.5 print(parse_en("1,234.5")) # 1234.5 -
Pandas: convert without crashing and isolate bad rows
pd.to_numeric(..., errors="coerce")replaces invalid values withNaN, so you can display them. TheInt64dtype (capital I) accepts missing values.read_csv()also handlesthousands,decimalandna_valuesdirectly.import pandas as pd df = pd.read_csv("users.csv", thousands=",", na_values=["N/A", "-"]) df["age"] = pd.to_numeric(df["age"], errors="coerce") print(df[df["age"].isna()]) # rows that could not be parsed df["age"] = df["age"].astype("Int64") # nullable integer
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Validate data at the boundary:
type=intinargparse, a Pydantic model for APIs, a schema for imported files. - With pandas, declare
dtype,na_values,thousandsanddecimalinread_csv()instead of converting afterwards. - Wrap every conversion of external data in a
try/except ValueErrorthat logs the bad value.
Frequently asked questions
How do I check whether a string is a number in Python?
The most reliable way is to try int(s) or float(s) in a try/except ValueError. str.isdigit() rejects negative and decimal numbers.
Why does int(3.5) work but not int('3.5')?
On a float, int() truncates the value. On a string, it expects an integer literal and rejects the decimal point. Use int(float('3.5')).
What does "with base 10" mean?
It is the base used to read the string. int('ff', 16) reads hexadecimal, int('0b101', 0) detects the prefix (0x, 0o, 0b) automatically.
Useful tools for this error
More Python errors
- Fix "ModuleNotFoundError: No module named" in Python
- Fix "IndentationError: unexpected indent" in Python
- Fix "'NoneType' object is not subscriptable" in Python
- Fix "error: externally-managed-environment" with pip
- Fix "UnicodeDecodeError: 'utf-8' codec can't decode byte" in Python
- Fix "KeyError" in Python (dict, pandas, os.environ)
- Fix "RecursionError: maximum recursion depth exceeded" in Python
- Fix "attempted relative import with no known parent package" in Python