Learn how to fix the Python error ‘invalid literal for int() with base 10’. In his article we will discover common causes and solutions for handling string to integer conversions.
The error invalid literal for int() with base 10 in Python occurs when you try to attempt to convert a non-numeric string into an integer using int()
. This guide explains why this error happens and how to fix it.
Table of Contents
How to Fix ‘invalid literal for int() with base 10’ in Python
So I’m going to share 5 quick fixes for invalid literal for int() with base 10. You can follow any of the method below and hopefully it will get the job done:
1. Ensure the String Contains Only Digits
Before converting a string to an integer, verify that it contains only numeric characters.
s = "123abc"
if s.isdigit():
num = int(s)
else:
print("Invalid input: Not a number")
2. Handle Empty Strings
An empty string will cause this error. Use a check before conversion:
s = ""
if s:
num = int(s)
else:
print("Invalid input: Empty string")
3. Convert Floating-Point Strings Properly
If you receive a floating-point number as a string, convert it to a float first:
s = "12.5"
num = int(float(s))
print(num) # Output: 12
4. Handle User Input Gracefully
If taking input from a user, use exception handling to avoid crashes:
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input: Please enter a valid integer.")
5. Remove Unwanted Characters
If the string contains extra spaces or symbols, clean it first:
s = " 42 " # Spaces around the number
num = int(s.strip())
print(num) # Output: 42
Why Does This Error Occur?
The error typically happens in the following scenarios:
- Trying to convert a string containing letters or special characters.
- Attempting to convert an empty string.
- Passing a floating-point number as a string.
- Reading data from files or user input that isn’t properly validated.
Conclusion
The ‘invalid literal for int() with base 10’ error occurs when Python encounters non-numeric data during integer conversion. By validating input and using exception handling, you can prevent this issue and write robust, error-free code.