ValueError: invalid literal for int() with base 10

Loading

The error message:

ValueError: invalid literal for int() with base 10

occurs when you try to convert a string to an integer, but the string contains characters that are not valid decimal numbers.


1. Causes and Solutions

Cause 1: Trying to Convert a Non-Numeric String to an Integer

Python’s int() function expects a valid number in string format. If the string contains letters, spaces, or special characters, it raises this error.

Incorrect Code:

num = int("abc")  # TypeError
num = int("12.34")  # TypeError (float-like string)
num = int("10a")  # TypeError (alphanumeric string)

Solution: Ensure the String Contains Only Digits

num = int("123")  # Works fine
print(num) # Output: 123

Alternative: Convert Float Strings Correctly

num = float("12.34")  # Convert to float first
print(int(num)) # Output: 12

Cause 2: String with Whitespace or Special Characters

If the string contains spaces or symbols like ,, $, or -, Python will not be able to parse it as an integer.

Incorrect Code:

num = int("  456 ")  # TypeError (extra spaces)
num = int("$500")  # TypeError (special character)

Solution: Clean the String Before Conversion

num = int("  456  ".strip())  # Works fine
print(num) # Output: 456
num = int("500".replace("$", ""))  # Remove special characters
print(num) # Output: 500

Cause 3: Trying to Convert an Empty String

An empty string "" is not a valid number.

Incorrect Code:

num = int("")  # TypeError

Solution: Check if the String is Empty Before Conversion

num_str = ""
if num_str:
num = int(num_str)
else:
print("Invalid input") # Output: Invalid input

Cause 4: Trying to Convert a Hexadecimal or Binary String

Python’s int() function, by default, works in base 10. If you try to convert hexadecimal (0x...) or binary (0b...) strings without specifying the correct base, you’ll get this error.

Incorrect Code:

num = int("0x1A")  # TypeError

Solution: Specify the Correct Base

num = int("1A", 16)  # Hexadecimal to integer
print(num) # Output: 26
num = int("1010", 2)  # Binary to integer
print(num) # Output: 10

Leave a Reply

Your email address will not be published. Required fields are marked *