Skip to content

/errors/python/valueerror-invalid-literal-for-int

ValueError: invalid literal for int() with base 10

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · Python 3.13.15updated
tool
Python
exit code
1
versions
Python 3.x
os
any

ValueError: invalid literal for int() with base 10: 'x' means int() received text that is not a whole number written in decimal. The value after the colon is the exact text that failed, which shows the cause: an empty string, a decimal point, a comma or a unit.

Reproduce it

bash
python -c "int('abc')"

Output · exit 1

Traceback (most recent call last):
  File "<string>", line 1, in <module>
    int('abc')
    ~~~^^^^^^^
ValueError: invalid literal for int() with base 10: 'abc'

Common inputs that fail:

bash
python - <<'PY'
for text in ['', ' ', '3.5', '1,000', '12px', '0x1f']:
    try:
        int(text)
    except ValueError as e:
        print(e)
PY

Output

invalid literal for int() with base 10: ''
invalid literal for int() with base 10: ' '
invalid literal for int() with base 10: '3.5'
invalid literal for int() with base 10: '1,000'
invalid literal for int() with base 10: '12px'
invalid literal for int() with base 10: '0x1f'

Fix it

bash
python - <<'PY'
print(int(' 42 '))
print(int('3.5'.split('.')[0]))
print(int(float('3.5')))
print(int('1,000'.replace(',', '')))
print(int('0x1f', 16))
PY

Output

42
3
3
1000
31

int() ignores surrounding spaces but not an empty string. A string with a prefix needs the base: int('0x1f', 16) or int('0x1f', 0). For user input, catch the error:

python
try:
    n = int(raw)
except ValueError:
    n = None

What int() accepts

int() parses an optional sign, digits and optional underscores between digits, with whitespace allowed around them. Everything else is rejected, including text that float() would accept:

bash
python - <<'PY'
for text in ['-7', ' +7\n', '1_000', '12.0', '1e3', 'age']:
    try:
        print(repr(text), '->', int(text))
    except ValueError as e:
        print(repr(text), '->', e)
try:
    int(None)
except TypeError as e:
    print('None ->', e)
PY

Output

'-7' -> -7
' +7\n' -> 7
'1_000' -> 1000
'12.0' -> invalid literal for int() with base 10: '12.0'
'1e3' -> invalid literal for int() with base 10: '1e3'
'age' -> invalid literal for int() with base 10: 'age'
None -> int() argument must be a string, a bytes-like object or a real number, not 'NoneType'

A trailing newline from a file line is not a problem, but a value like 'age' is: it is the classic sign that the header row of a CSV file was converted along with the data.

How to recognise the cause

The text after the colon, shown with repr() quotes, tells you which case you hit:

Text in the messageCauseFix
''Empty input or a blank cellCheck for empty strings and use a default
'3.5' or '12.0'Decimal valueint(float(text)), or Decimal for exact values
'1,000' or '$5'Formatting charactersRemove them before converting
'age' or 'id'A header row or a labelSkip the header or use csv.DictReader
'0x1f' or '0b101'A prefixed literalPass the base, int(text, 0) or int(text, 16)

If the message shows with base 16 or another base, the base was passed explicitly and the text contains a digit that is not valid in that base.

Prevention

Validate input where it enters the program: strip it, reject empty values with a clear message, and convert in one place with try/except ValueError. For CSV data, read it with csv.DictReader so the header never reaches int(). When thousands separators depend on the user's locale, parse with locale.atoi() after setting the locale instead of removing characters by hand.

FAQ

Why does int('12.0') fail when int(12.0) works?

int() on a float truncates the number, but int() on a string only parses digits. Convert with float() first, int(float('12.0')), if the text may contain a decimal part.

Does int() accept underscores and signs?

Yes. Leading + or -, surrounding whitespace and single underscores between digits, as in '1_000', are accepted. Commas, spaces between digits and units are not.

Why do I get a TypeError instead of a ValueError?

int(None) or int([1]) raise TypeError because the argument is not a string or a number at all. ValueError means the type was right but the text is not a valid integer.

Sources