ValueError: invalid literal for int() with base 10
ValueError: invalid literal for int() with base 10
DodaTech
3 min read
ValueError: invalid literal for int() with base 10 occurs when you pass a string to int() that doesn’t look like a valid integer. The string must contain only digits (with optional leading + or -).
What It Means
The int() function expects a string like "42" or "-7" but received something else — maybe "42.5", "4,2", "abc", or " 42 " with whitespace. Any non-digit character (except a leading sign) causes this error.
Why It Happens
- String contains whitespace:
" 42 "(note:int(" 42")actually works in Python 3, butint("42 ")fails) - String has commas or decimal points:
"4,200"or"3.14" - String is empty:
"" - String is not numeric:
"abc","ten" - String has leading zeros that don’t affect parsing but might indicate bad data
- User input wasn’t validated before conversion
How to Fix It
Step 1: Strip whitespace and non-digit characters
# BAD
user_input = " 42 "
value = int(user_input) # Some of these may work, but be explicit
# GOOD — strip first
value = int(user_input.strip())Step 2: Remove commas and decimal points
price = "4,200"
# BAD
int(price) # ValueError
# GOOD — remove commas first
value = int(price.replace(",", ""))
# For floats, convert to float first, then int
decimal_str = "3.14"
value = int(float(decimal_str)) # 3Step 3: Validate before converting
user_input = input("Enter a number: ")
if user_input.isdigit() or (user_input.startswith("-") and user_input[1:].isdigit()):
value = int(user_input)
else:
print(f"'{user_input}' is not a valid integer")Step 4: Use try/except for robust conversion
def safe_int(value, default=None):
try:
return int(value)
except (ValueError, TypeError):
return default
# Usage
result = safe_int("42") # 42
result = safe_int("abc") # None
result = safe_int("abc", 0) # 0Step 5: Handle empty strings
user_input = input("Enter a number: ").strip()
if not user_input:
print("Input cannot be empty")
else:
try:
value = int(user_input)
except ValueError:
print(f"'{user_input}' is not a valid integer")Step 6: Fix common number format issues
# Currency symbols
amount = "$42"
value = int(amount.replace("$", "")) # 42
# Percentage
pct = "85%"
value = int(pct.replace("%", "")) # 85
# Spaces around
text = " 42 "
value = int(text.strip()) # 42
# Negative sign with space
text = "- 42"
value = int(text.replace(" ", "")) # -42 Previous
java.io.FileNotFoundException
Next
You have divergent branches and need to specify how to reconcile them
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro