Skip to content
  1. LuzineDebug
  2. Python
  3. ValueError: invalid literal for int() with base…
Python Beginner ≈ 5 min to fix

Fix "ValueError: invalid literal for int() with base 10" in Python

Error message
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
In short

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.

Be the first to confirm this fix

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

  1. Unvalidated user input: int(input()) when the user types text or just presses Enter (empty string '').
  2. Decimal number as text: int('3.5') always fails, even though the value looks like a number.
  3. Regional format or unit: thousands separators ('1,234', '1 234'), decimal comma ('1,5'), currency symbol or percentage ('12€', '45%').
  4. Dirty CSV or Excel file: empty cells, 'N/A', '-', or a header row processed as data (int('age')).
  5. 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

  1. Read the value shown in the message

    The end of the message shows exactly what int() received. If needed, print it with repr() right before the conversion to see spaces, invisible characters and the type.

    python
    print(repr(value), type(value))
  2. Validate input with try/except

    For 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 '²'.

    python
    while True:
        raw = input("Age: ").strip()
        try:
            age = int(raw)
            break
        except ValueError:
            print(f"{raw!r} is not a whole number, try again.")
  3. Convert a decimal string

    Go through float() then choose explicitly: truncate with int(), round with round() (round half to even: round(2.5) is 2), or keep exact precision with Decimal for amounts.

    python
    from decimal import Decimal
    
    value = "3.5"
    truncated = int(float(value))   # 3
    rounded = round(float(value))   # 4
    exact = Decimal(value)          # Decimal('3.5')
  4. 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.

    python
    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
  5. Pandas: convert without crashing and isolate bad rows

    pd.to_numeric(..., errors="coerce") replaces invalid values with NaN, so you can display them. The Int64 dtype (capital I) accepts missing values. read_csv() also handles thousands, decimal and na_values directly.

    python
    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=int in argparse, a Pydantic model for APIs, a schema for imported files.
  • With pandas, declare dtype, na_values, thousands and decimal in read_csv() instead of converting afterwards.
  • Wrap every conversion of external data in a try/except ValueError that 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

All Python errors →