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

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
5 min

banner

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

The Python "ValueError: invalid literal for int() with base 10" occurs when we pass a string that cannot be directly converted to an integer to the int() class.

Common causes of the error are:

  • trying to convert a string that is a floating-point number to an integer with int().
  • trying to convert an empty string or one that only contains spaces to an integer.
  • trying to convert a string that contains non-digit characters with int().

python valueerror invalid literal for int with base 10

Here are 3 examples of how the error occurs.

main.py
# ⛔️ ValueError: invalid literal for int() with base 10: '5.0' print(int('5.0')) # ⛔️ ValueError: invalid literal for int() with base 10: '' print(int('')) # ⛔️ ValueError: print(int('a2c3'))

We can't directly pass a string that contains a float to the int() class because the class expects a value with base 10 (where each digit can have an integer value ranging from 0 to 9 - 10 possibilities).

main.py
my_str = '5.6' # ✅ Convert to a float first my_float = float(my_str) my_int = int(my_float) print(my_int) # 👉️ 5 print(type(my_int)) # 👉️ <class 'int'>

convert to float first

Another common cause of the error is passing a string that contains non-digit characters to the int() class.

The int() class expects a string that is a valid integer.

main.py
# ✅ a string that is a valid integer my_str = '123456' my_int = int(my_str) print(my_int) # 👉️ 123456

int class expects a string

The int() class parses the string in the example without any issues because:

  1. It is not a floating-point number.
  2. It does not contain non-digit characters (e.g. symbols, letters or special characters).

# Dealing with strings that contain non-digit characters

The error is often raised when you pass a string that contains non-digit characters to the int() class.

main.py
my_str = 'a2c3' # ⛔️ ValueError: invalid literal for int() with base 10: 'a2c3' print(int(my_str))

When taking user input with the input() function, the value is always going to be converted to a string, even if the user enters an integer.

Therefore, we have to use the int() class to convert the string values to integers.

main.py
num_1 = int(input('Enter a number: ')) num_2 = int(input('Enter another number: ')) result = num_1 + num_2 print(result)

converting invalid strings to int

However, as shown in the gif, this can cause issues if the user enters a value that is not a valid integer.

You can use a try/except statement to handle the error.

main.py
try: num_1 = int(input('Enter a number: ')) num_2 = int(input('Enter another number: ')) result = num_1 + num_2 print(result) except ValueError: print('Invalid integer value supplied.')

using try except to handle the error

The code sample uses a try/except statement to handle the error.

If the user provides an invalid integer, the call to the int() class raises a ValueError and the except block is run.

The error is handled in the except block, so it no longer crashes the program.

If taking floating-point numbers from user input, use the float() class in the place of int().

# Dealing with floating-point numbers that are wrapped in a string

If your string is a valid floating-point number, convert the string to a float before passing it to the int() class.

main.py
my_str = '5.6' my_float = float(my_str) my_int = int(my_float) print(my_int) # 👉️ 5 print(type(my_int)) # 👉️ <class 'int'>

dealing with floating point numbers that are wrapped in string

The float() class takes care of converting the string to a floating-point number and the int() class converts the float to an integer.

When the floating-point number is passed to the int() class, it gets truncated.

If you need to round the float to an integer, use the:

  • round() function to round to the nearest integer.
main.py
my_str = '5.6' my_int = round(float(my_str)) print(my_int) # 👉️ 6 print(type(my_int)) # 👉️ <class 'int'>
main.py
import math my_str = '5.1' my_int = math.ceil(float(my_str)) print(my_int) # 👉️ 6 print(type(my_int)) # 👉️ <class 'int'>
main.py
import math my_str = '5.999' my_int = math.floor(float(my_str)) print(my_int) # 👉️ 5 print(type(my_int)) # 👉️ <class 'int'>

# Dealing with empty strings

Make sure to print() the value you are passing to the int class as it may not contain what you expect.

For example, you might be passing an empty string or a string that contains a space to the int() class.

main.py
val = ' ' result = int(val.strip() or 0) print(result) # 👉️ 0

The str.strip() method returns a copy of the string with the leading and trailing whitespace removed.

If removing all leading and trailing whitespace from the string returns an empty string, we pass 0 to the int() class.

Alternatively, you can use an if/else statement to check if the string is empty before passing it to int().

main.py
my_str = ' ' if my_str.strip(): my_int = int(my_str) else: # 👇️ this runs print('The specified string is empty')

The string in the example contains only spaces, so it doesn't pass the test in the if statement and the int() class is never called.

# Using a try/except statement to handle the error

You can also use a try/except block to handle the error.

main.py
val = 'abc' try: result = int(val) except ValueError: result = 0 print(result) # 👉️ 0

If calling the int() class with the value raises a ValueError, the except block runs where we set the result variable to 0.

# Only extracting the integers from the string

If you have a string that may also contain characters but you only need to extract an integer, use the filter() function to filter out all non-digits.

main.py
my_str = 'a40b' my_num_1 = int(''.join(filter(str.isdigit, my_str))) print(my_num_1) # 👉️ 40

The filter() function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

The str.isdigit() method returns True if all characters in the string are digits and there is at least 1 character, otherwise False is returned.

We basically check if each character in the string is a digit, return the result and join the digits into a single string before using the int() class to get an integer value.

# When to call the int() and float() classes

  1. The int() class can be called with the string representation of an integer.
main.py
my_str = '12345' my_int = int(my_str) print(my_int) # 👉️ 12345
  1. The float() class can be called with the string representation of a float.
main.py
my_str = '123.45' my_float = float(my_str) print(my_float) # 👉️ 123.45
  1. The float() class can be called with the string representation of an integer.
main.py
my_str = '12345' my_float = float(my_str) print(my_float) # 👉️ 12345.0
  1. The int() class can be called with a floating-point number.
main.py
my_float = 123.99 my_int = int(my_float) print(my_int) # 👉️ 123
  1. The float() class can be called with an integer.
main.py
my_int = 1234 my_float = int(my_int) print(my_float) # 👉️ 1234

These are the only valid calls you can make to the int() and float() classes in Python.

# Conclusion

To solve the Python "ValueError: invalid literal for int() with base 10" error:

  1. Pass only strings that don't contain any non-digit characters to the int() class.
  2. Use the float() class before calling int() when converting strings that are floating-point numbers to integers.
  3. Make sure the string is not empty or contains only spaces.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.