Python Error Guide: 'ValueError: invalid literal for int() with base 10' — Cause, Fix, and Troubleshooting Guide
Fix Python 'ValueError: invalid literal for int() with base 10': strip whitespace, validate input, handle empty strings and decimals before int() conversion.
- #python
- #automation
- #troubleshooting
- #errors
Stuck on this Bash & Python Automation error? Get the free incident triage checklist
A one-page PDF — the exact steps to isolate, fix, and verify a production error like this one. No spam, unsubscribe anytime.
Overview
Python raises this when int() is handed a string it can’t parse as a base-10 integer:
ValueError: invalid literal for int() with base 10: '1,024\n'
int() is strict: it accepts optional surrounding whitespace and a leading sign, then requires nothing but digits. A comma, a decimal point, a stray newline, an empty string, or any non-digit character makes it refuse. The repr in the message ('1,024\n') shows the exact offending value including hidden characters — read it carefully, because the culprit is often a \n or space you didn’t know was there.
Symptoms
- The message quotes the bad value with its repr, sometimes revealing
\n,\t, or surrounding spaces. - Conversion works for clean inputs but fails on data from files, CSVs, env vars, or API responses.
- An empty string (
'') triggers it — common when a field is missing or a line is blank. - Values that look numeric to a human (
3.5,1,000,12px,0x1F) fail base-10int().
Common Root Causes
- Trailing newline/whitespace — reading a line without stripping (
int(line)whereline == '42\n'… actuallyint()tolerates surrounding whitespace, but embedded characters and empty strings do not). - Empty string — a missing field or blank line:
int(''). - Decimal or float string —
int('3.5')fails; usefloat()first orint(float(...)). - Thousands separators / units —
'1,024','12px','2GB'. - A non-base-10 literal —
'0x1F','0b101'without the matchingbase=argument. - A whole non-numeric token — a header row, a label, or
'N/A'slipping into numeric parsing.
Diagnostic Workflow
Print the repr of the value before converting so hidden characters are visible:
print(repr(value)) # '1,024\n' vs '1024' tells you everything
Guard the conversion and log the offender:
try:
n = int(value)
except ValueError:
print(f"not an int: {value!r}")
raise
For file/CSV data, check whether a header row or blank line is leaking in:
head -3 data.csv # is row 1 a header of column names?
Example Root Cause Analysis
A script summed a metrics column from a CSV:
total = 0
with open("metrics.csv") as fh:
for line in fh:
total += int(line.split(",")[1])
It failed on the very first row:
ValueError: invalid literal for int() with base 10: 'count'
The repr 'count' gave it away: line 1 was a header row, so line.split(",")[1] was the column name count, not a number. A second latent bug lurked too — a trailing '42\n' on data rows and possible blank lines. The robust fix uses csv.DictReader (which handles the header) and validates each value:
import csv
total = 0
with open("metrics.csv", newline="") as fh:
for row in csv.DictReader(fh):
raw = (row.get("count") or "").strip()
if not raw:
continue # skip blank/missing
try:
total += int(raw)
except ValueError:
print(f"skipping non-numeric count: {raw!r}")
Now the header is consumed automatically, blanks are skipped, and any stray non-numeric value is reported instead of crashing the run.
Prevention Best Practices
- Strip and validate before converting —
value.strip()and check it’s non-empty; considerstr.isdigit()for unsigned integers (note: it rejects signs and is Unicode-aware). - Use
csv.DictReaderfor CSVs so header rows and columns are handled correctly. - Handle empty/missing explicitly — default with
int(value or 0)only when zero is truly the right fallback. - For decimals, go through
float—int(float('3.5'))if truncation is intended. - Wrap conversions in
try/except ValueErrorat data boundaries and log the offending repr. - Pass
base=0to accept0x/0bprefixes if you must parse mixed-radix literals.
Quick Command Reference
print(repr(value)) # reveal hidden \n, spaces, commas
int(value.strip()) # trim surrounding whitespace first
int(value or 0) # default empty string to 0 (if apt)
int(float("3.5")) # 3 — go via float for decimals
int("0x1F", 0) # honor 0x/0b prefixes with base=0
value.strip().isdigit() # cheap pre-check for unsigned ints
Related Guides
- Python Error Guide: ‘json.decoder.JSONDecodeError: Expecting value’ — a related data-parsing failure at input boundaries.
- Bash Error Guide: ‘printf: invalid number’ — the Bash equivalent when formatting non-integer values.
- Bash & Python Error Guide: ‘TypeError: NoneType object is not subscriptable’ — another error from unvalidated data flowing through a script.
Conclusion
ValueError: invalid literal for int() with base 10 is int() refusing a string that isn’t clean digits — a header row, a blank field, a decimal, a comma, or a hidden \n. Read the repr in the message to see the exact offender, strip and validate at the data boundary, use csv.DictReader for CSVs, and wrap conversions in try/except ValueError that logs what it skipped. Validate input where it enters the script and numeric parsing stops crashing on messy data.
Fixed it? Get 500 Bash & Python Automation & DevOps AI prompts — free
500 battle-tested, copy-paste AI prompts engineered by a senior systems engineer — every one with fill-in placeholders and safety/back-out notes. Drop your email and it's yours.
- 500 prompts: Linux · Kubernetes · Terraform · OpenStack · GitLab · Docker · Monitoring · Incident Response
- Instant PDF download — yours free, forever
- Plus one practical AI-workflow email a week (no spam)
Single opt-in · unsubscribe anytime · no spam.
Did this fix your issue?
Get 500 Battle-Tested DevOps AI Prompts — Free
500 battle-tested, copy-paste AI prompts engineered by a senior systems engineer — every one with fill-in placeholders and safety/back-out notes. Drop your email and it's yours.
- 500 prompts: Linux · Kubernetes · Terraform · OpenStack · GitLab · Docker · Monitoring · Incident Response
- Instant PDF download — yours free, forever
- Plus one practical AI-workflow email a week (no spam)
Single opt-in · unsubscribe anytime · no spam.