Skip to content

How to Fix ValueError: invalid literal for int() in Python

DodaTech Updated 2026-06-24 2 min read

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-except blocks when converting external data.
  • Use str.isdigit() or str.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

  1. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  2. Misunderstanding that String is [Char] with poor performance for large text operations
  3. Using foldl instead of foldl' 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

### What does "invalid literal" mean in this context?

A literal is the actual string value you passed to int(). "Invalid literal" means the string content cannot be interpreted as an integer. For example, "12.5", "abc", and "" are all invalid literals for int().

Does int() handle whitespace?

Yes, int() strips leading and trailing whitespace by default. int(" 42 ") works fine. But int("42 ") with a space after is OK too. The problem is non-numeric characters within the string.

Why does int() not accept decimal strings?

int() expects a string representation of an integer, not a float. Use int(float("3.14")) to convert a decimal string to an integer. The two-step conversion truncates the decimal portion.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro