ValueError: invalid literal for int() with base 10 — the fix

int() converts a string to an integer only if the string is exactly an integer: digits, an optional sign, nothing else. "3.5", "1,000", "" and "abc" all fail with this message — and the message quotes the offending string, which is the first thing to look at.

The fix, in order

  1. Read the quoted value in the error. The problem is usually visible at a glance: it’s a decimal, not an integer.
  2. Decimals: convert via float first — int(float("3.5")) gives 3. If you actually need the fraction, keep it a float and don’t convert at all.
  3. User input: strip and validate before converting. text = raw.strip() removes stray spaces and newlines; then wrap the conversion in try/except ValueError and ask again.
  4. Thousands separators and currency symbols must come out first: int("1,000".replace(",", "")). Data from spreadsheets and web pages is full of these.
  5. Empty string means the value never arrived — a blank form field, an empty file line, a missing argument. Fix the source rather than the conversion: default it, skip the line, or report it clearly.

If it still happens

If the string looks like a clean number and still fails, suspect invisible characters — a non-breaking space or a BOM copied from a web page. Print `repr(text)` to see the actual characters; repr never lies.

Common questions

Why does int("3.0") fail? It’s basically 3. Because int() parses integer syntax only, and "3.0" isn’t it. int(float("3.0")) is the standard route.

What’s the safest pattern for converting user input? try/except around the conversion: handle the failure where it happens, with a message the user can act on. Checks like isdigit() miss negative numbers and decimals, so try/except is the honest tool.

Related errors

KeyError · TypeError: 'NoneType' object is not subscriptable · IndentationError: unexpected indent