← Debugging Guides

阅读中文版本

Python ValueError — Invalid Literal for int()

Fix ValueError invalid literal for int() with base 10 by identifying the non-numeric token and parsing it with explicit handling of whitespace and signs.

beginnerdebuggingpythonvalueerrorparsing

Symptoms

  • Python raises "ValueError: invalid literal for int() with base 10: '...'"
  • Works for numeric strings but fails on CSV cells with spaces or symbols
  • A config value that looks like a number refuses to convert

Possible causes

  • The string contains whitespace, currency symbols, or thousands separators
  • A floating-point value such as "3.14" is passed to int()
  • An empty string or "None" from a form field reaches int()

Diagnosis steps

Reproduce and read the offending literal

python -c "print(int(' 42 '))"

Interpretation

int tolerates surrounding whitespace, so if this fails the token has extra characters.

Inspect the raw value

print(repr(raw))

Interpretation

repr reveals hidden characters such as non-breaking spaces or a trailing comma.

Root cause

int(str) accepts only an optional sign followed by digit characters, plus surrounding whitespace. Any other character, a decimal point, or an empty string raises ValueError before conversion.

Fix

Clean the token first (strip whitespace and separators), choose int versus float deliberately, and guard with try/except or a validation helper that reports the bad value.

Risk note

Stripping all non-digits turns "12abc" into 12 and hides corrupt data; validate rather than silently coercing.

Verify the fix

Rerun with the original bad input and confirm a controlled error or a correct parsed value. Add tests for whitespace, decimals, and empty strings.

Symptoms

This debugging guide addresses “Python ValueError — Invalid Literal for int()”. Start from the symptoms, follow the ordered diagnostics, and confirm each hypothesis before moving on; the fix and verification steps then close the loop.

Observed symptoms include:

  • Python raises “ValueError: invalid literal for int() with base 10: ‘…’”
  • Works for numeric strings but fails on CSV cells with spaces or symbols
  • A config value that looks like a number refuses to convert

Reproduce and Diagnose

Reproduce the failure in isolation before changing any code. Work through the checks below in order; each one narrows the search space.

Step 1: Reproduce and read the offending literal

python -c "print(int(' 42 '))"

int tolerates surrounding whitespace, so if this fails the token has extra characters.

Step 2: Inspect the raw value

print(repr(raw))

repr reveals hidden characters such as non-breaking spaces or a trailing comma.

Likely contributors, in order of frequency:

  • The string contains whitespace, currency symbols, or thousands separators
  • A floating-point value such as “3.14” is passed to int()
  • An empty string or “None” from a form field reaches int()

Root Cause

int(str) accepts only an optional sign followed by digit characters, plus surrounding whitespace. Any other character, a decimal point, or an empty string raises ValueError before conversion.

The Fix

Clean the token first (strip whitespace and separators), choose int versus float deliberately, and guard with try/except or a validation helper that reports the bad value.

Watch out: Stripping all non-digits turns “12abc” into 12 and hides corrupt data; validate rather than silently coercing.

def to_int(raw):
    s = str(raw).strip().replace(',', '')
    if not s:
        raise ValueError('empty numeric field')
    try:
        return int(s)
    except ValueError:
        return int(float(s))  # tolerate '3.14' and '3e2'

print(to_int(' 1,024 '))

Verify and Prevent

Rerun with the original bad input and confirm a controlled error or a correct parsed value. Add tests for whitespace, decimals, and empty strings.

Once verified, add a regression test that reproduces the original symptom so the failure cannot silently return.

This class of failure is usually environmental rather than pure logic, so capture the exact command, the environment variables, and the working directory in your bug report. Reproduce it in the smallest possible script, then widen the scope only once the minimal case is understood. A short written checklist for this failure mode saves hours the next time it appears.