How to Fix ValueError: invalid literal for int() in Python
In this tutorial, you'll learn about How to Fix ValueError: invalid literal for int() in Python. We cover key concepts, practical examples, and best practices.
Python raises ValueError: invalid literal for int() with base 10 when you pass a string that does not represent a valid integer to the int() function.
The Wrong Way
number = int("abc")
print(number)
This produces:
Traceback (most recent call last):
File "script.py", line 1, in <module>
number = int("abc")
ValueError: invalid literal for int() with base 10: 'abc'
The Right Way
Validate the input before conversion, or use a try-except block:
value = "abc"
if value.isdigit():
number = int(value)
else:
number = 0
print(f"Warning: '{value}' is not a valid integer")
print(number)
Output:
Warning: 'abc' is not a valid integer
0
Step-by-Step Fix
1. Strip whitespace from input
User input often contains trailing newlines or spaces:
# Wrong
user_input = " 42\n"
number = int(user_input) # ValueError for whitespace? Actually int() handles whitespace
# More problematic input
user_input = "42 "
number = int(user_input) # This works, but careful with other cases
# Problem case
user_input = "$42"
number = int(user_input) # ValueError
The robust approach:
import re
user_input = "$42"
match = re.search(r'-?\d+', user_input)
if match:
number = int(match.group())
else:
number = 0
2. Use try-except for untrusted input
def safe_int(value, default=0):
try:
return int(value)
except (ValueError, TypeError):
return default
print(safe_int("42"))
print(safe_int("abc"))
print(safe_int(None))
Output:
42
0
0
3. Check for decimal strings
# Wrong -- int() does not accept decimal strings directly
number = int("3.14") # ValueError
# Right
number = int(float("3.14"))
print(number)
Output:
3
Prevention Tips
- Always validate or sanitize user input before type conversion.
- Use
try-exceptblocks when converting external data. - Use
str.isdigit()orstr.strip()for basic validation. - Use
re.match(r'^-?\d+$', value)for strict integer validation. - Use
pandas.to_numeric()for bulk data conversion with error handling.
Common Mistakes with valueerror
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro