The ValueError: invalid literal for int() with base 10 error in Python occurs when you try to convert a string to an integer using the int() function, but the string isn't a valid integer. Here's how you can fix this issue:

1. Check the Input String

Ensure that the string you're trying to convert contains only digits and optionally a leading '+' or '-' sign. If the string has non-numeric characters, int() will raise this error.

value = "1234"
number = int(value)  # This will work fine.

If the string contains non-numeric characters:

2. Handle Non-Numeric Characters

value = "1234abc"
number = int(value)  # This will raise the ValueError

If the string may contain non-numeric characters, you can clean the string or use a try-except block to handle the error.

Example with string cleaning:

value = "1234abc"
cleaned_value = ''.join(filter(str.isdigit, value))
number = int(cleaned_value)
print(number)  # Output will be 1234

Example with try-except block:

value = "1234abc"
try:
    number = int(value)
except ValueError:
    print("The input string is not a valid integer.")

3. Check for Empty Strings

An empty string will also raise this error when passed to int():

value = ""
number = int(value)  # This will raise ValueError

Fix:

value = ""
if value.strip():  # Checks if the string is not empty or just whitespace
    number = int(value)
else:
    print("The string is empty.")

4. Ensure Correct Base

If the string represents a number in a different base (e.g., binary, hexadecimal), specify the correct base as the second argument to int():

value = "1010"
number = int(value, 2)  # Converts the binary string to an integer (output will be 10)

5. Check for Leading or Trailing Whitespace

Strings with leading or trailing whitespace can sometimes cause issues:

value = "  1234  "
number = int(value.strip())  # Using strip() to remove whitespace before conversion

By applying these steps, you can identify the specific issue causing the ValueError and resolve it accordingly.

Neha

5 Articles