Fix ValueError: invalid literal for int() with base 10 in Python

This error occurs when you try to convert a non-integer string or a string containing non-numeric characters to an integer using the int() function in Python. To fix this error, you need to ensure that the input to int() is a valid integer string.

Here’s an example of what might cause the error:

python

number = "123a"
int_number = int(number)  # This will raise a ValueError

To fix this error, you can follow one of the following approaches:

  1. Validate the input: Check if the input string contains only numeric characters before converting it to an integer.

python

def is_valid_integer(s):
    return s.isdigit() or (s.startswith('-') and s[1:].isdigit())

number = "123a"

if is_valid_integer(number):
    int_number = int(number)
else:
    print(f"The input '{number}' is not a valid integer.")
  1. Use exception handling: Catch the ValueError exception and handle the error case.

python

number = "123a"

try:
    int_number = int(number)
except ValueError:
    print(f"The input '{number}' is not a valid integer.")
  1. Remove non-numeric characters: If you want to convert a string containing digits and non-numeric characters to an integer, you can remove the non-numeric characters before converting it.

python

number = "123a"

# Remove non-numeric characters
filtered_number = "".join(c for c in number if c.isdigit())

# Convert the filtered string to an integer
int_number = int(filtered_number)

Choose the approach that best suits your needs and apply it to your code to fix the ValueError: invalid literal for int() with base 10 error.

Facebook
Twitter
LinkedIn
Pinterest

Table of Contents

Related posts