How to fix "ValueError: invalid literal for int() with base 10" in Python
Last Updated :
28 Apr, 2025
This error occurs when you attempt to convert a string to an integer using the int() function, but the string is not in a valid numeric format. It can happen if the string contains non-numeric characters, spaces, symbols. For example, converting a string like "abc" or "123.45" to an integer will trigger this error, as Python expects a valid integer string (e.g., "123") without any extraneous characters or formatting.
Causes of the ValueError: invalid literal for int() with base 10
There are several reasons why this error occurs:
- Non-numeric characters in the input string: The input string contains characters that are not digits, such as alphabetic characters or special symbols.
- Incorrectly formatted strings: The string might have punctuation marks, spaces, or characters that are not allowed in an integer representation.
- Leading or trailing spaces: If the string contains spaces before or after the number, it can lead to an error.
- Punctuation marks: Periods, commas or other special characters in the string will cause the error.
Examples of common scenarios leading to this error
Example 1: In this example, we try to convert the string "abc123" to an integer using int(), but it contains letters, making it an invalid base-10 number and causing a ValueError.
Python
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 1, in <module>
a = int("abc123")
ValueError: invalid literal for int() with base 10: 'abc123'
Example 2: In this example, we try to convert the string " 4 2 " to an integer using int(), but it contains extra spaces within the number, making it an invalid base-10 format and resulting in a ValueError.
Python
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 1, in <module>
a = int(" 4 2 ")
ValueError: invalid literal for int() with base 10: ' 4 2 '
Example 3: In this example, we try to convert "19.3" to an integer using int(), but the period (.) indicates a float, causing a ValueError since int() expects a whole number like "19".
Python
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 2, in <module>
b = int(a)
ValueError: invalid literal for int() with base 10: '19.3'
Solutions to Fix "ValueError: invalid literal for int() with base 10"
Here are several ways to resolve this error:
1. Check and Clean Input Strings: Before converting a string to an integer, ensure that the string contains only valid numeric characters. You can remove any unwanted characters or spaces before conversion.
Python
a = int("123")
b = int(" 42 ".strip())
print(b)
Explanation:
- int("123") converts the string "123" directly to the integer 123.
- int(" 42 ".strip()) removes leading spaces from " 42 " using strip() and converts the resulting string "42" to the integer 42.
2. Stripping Whitespace: Leading and trailing spaces are common causes of this error. You can use the strip() method to remove the spaces before attempting conversion.
Python
a = " 123 "
b = int(a.strip())
print(b)
Explanation: int(a.strip()) removes the spaces, resulting in the string "123", which is then converted to the integer 123.
3. Validate Input Before Conversion: Use methods like isdigit() to check whether the string consists only of numeric characters before attempting to convert it. This can help avoid errors by ensuring the string is in a valid format.
Python
a = "123"
if a.isdigit():
b = int(a)
print(b)
else:
print("Invalid")
Explanation: isdigit() method checks if a string contains only digits. Since "123" is valid, it's safely converted to an integer. If not, the else block prints "Invalid", avoiding a ValueError.
Alternative approach
1. Using try-except blocks: When you're unsure about the format of the input string, using a try-except block can help handle the error without crashing the program.
Python
try:
value = int("abc123")
except ValueError:
print("Invalid")
Explanation: try-except block attempts to convert "abc123" to an integer. Since it contains letters, int() raises a ValueError, which is caught and "Invalid" is printed to prevent a crash.
2. Check for floating-point numbers: If the input might contain floating-point numbers (e.g., "19.3"), you can use float() for conversion, followed by rounding or handling decimals as needed.
Python
a = "19.3"
b = float(a)
print(b)
Explanation: string "19.3" is converted to a float using float(a). Since it's a valid decimal number, the conversion succeeds and 19.3 is printed.
Similar Reads
What is the meaning of invalid literal for int() with base = ' '?
ValueError is encountered when we pass an inappropriate argument type. Here, we are talking about the ValueError caused by passing an incorrect argument to the int() function. When we pass a string representation of a float or any string representation other than that of int, it gives a ValueError.
2 min read
How to Fix "TypeError: 'float' object is not callable" in Python
In Python, encountering the error message "TypeError: 'float' object is not callable" is a common issue that can arise due to the misuse of the variable names or syntax errors. This article will explain why this error occurs and provide detailed steps to fix it along with the example code and common
4 min read
How to Fix "TypeError: list indices must be integers or slices, not float" in Python
Python is a versatile and powerful programming language used in various fields from web development to data analysis. However, like any programming language, Python can produce errors that might seem confusing at first. One such common error is the TypeError: list indices must be integers or slices
4 min read
How to Fix: ValueError: cannot convert float NaN to integer
In this article we will discuss how to fix the value error - cannot convert float NaN to integer in Python. In Python, NaN stands for Not a Number. This error will occur when we are converting the dataframe column of the float type that contains NaN values to an integer. Let's see the error and expl
3 min read
How to Fix "TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'" in Python
The TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' error in Python occurs when attempting to concatenate a NoneType object with the string. This is a common error that arises due to the uninitialized variables missing the return values or improper data handling. This article will
4 min read
Fix The Syntaxerror: Invalid Token In Python
Python is a popular and flexible programming language that provides developers with a strong toolkit for creating a wide range of applications. Even seasoned programmers, though, occasionally run into problems when developing; one such issue is SyntaxError: Invalid Token. The unexpected characters o
3 min read
How to fix - "typeerror 'module' object is not callable" in Python
Python is well known for the different modules it provides to make our tasks easier. Not just that, we can even make our own modules as well., and in case you don't know, any Python file with a .py extension can act like a module in Python. In this article, we will discuss the error called "typeerr
4 min read
How to input multiple values from user in one line in Python?
The goal here is to take multiple inputs from the user in a single line and process them efficiently, such as converting them into a list of integers or strings. For example, if the user enters 10 20 30 40, we want to store this as a list like [10, 20, 30, 40]. Letâs explore different approaches to
2 min read
How to Fix: SyntaxError: positional argument follows keyword argument in Python
In this article, we will discuss how to fix the syntax error that is positional argument follows keyword argument in Python An argument is a value provided to a function when you call that function. For example, look at the below program - Python Code # function def calculate_square(num): return num
3 min read
How to Replace Values in a List in Python?
Replacing values in a list in Python can be done by accessing specific indexes and using loops. In this article, we are going to see how to replace the value in a List using Python. We can replace values in the list in several ways. The simplest way to replace values in a list in Python is by using
2 min read