[SOLVED] ValueError: invalid literal for int() with base 10

[toc]

Introduction

Problem: How to fix “ValueError: invalid literal for int() with base 10“?

In Python, you can convert the values of one type into another. That means you can convert the integer strings into integers, integers into floats, floats into strings, etc. But one such conversion that Python dislikes is to change a float structured string to an integer. Thus, in this article, we will see what happens when you try to do so and dive into ValueError: invalid literal for int() with base 10 error.

A Quick Recap to int()

Python int() Graphical Explanation

Before diving into the topic of our discussion, it is extremely important to understand the working principle of the int() method. In Python, the int() function is used to take a string or a number as the first argument and a  contention base which signifies the format of the number. The base generally has a default value of 10 which is utilized for decimal numbers. However, we can pass an alternate value for bases like 2 for binary numbers and 16 for hexadecimal numbers.

Recommended Read: Here’s a detailed discussion on Python’s built-in metod int() – Python int() Function

ValueError: invalid literal for int() with base 10

When you pass any non-integer value as a string inside the int() method, you will get the following error: ValueError: invalid literal for int() with base 10. In simple words, it means that you tried to convert an input to an integer using function int() which has characters other than the numbers in the decimal number system.

Let’s try to understand this with the help of an example:

integer_string = '100'  # This is an integer string
decimal_no = '100.20'   # This is a float string
normal_string = 'FINXTER'   # This is a normal string
res_1 = int(integer_string)
print("Converting integer string to integer: ", res_1)
res_2 = int(decimal_no)
print("Converting Decimal String to integer: ", res_2)
res_3 = int(normal_string)
print("Converting string to integer: ", res_3)

Output:

Converting integer string to integer:  100
Traceback (most recent call last):
  File "C:\Users\SHUBHAM SAYON\PycharmProjects\Finxer\Errors\ValueError-invalid literal for int.py", line 6, in <module>
    res_2 = int(decimal_no)
ValueError: invalid literal for int() with base 10: '100.20'

From the above example it is evident that the integer string was converted to an integer successfully. However, this wasn’t the case for the float string or the normal string which led to the occurrence of the ValueError.

Now, let’s have a look at a few ways to eliminate or avoid this error.

Method 1: Using isdigit()

One approach to deal with this problem is to check whether the given input is an integer or not using the isdigit() method. If the given input is a valid digit, then you have to convert it to an integer else you can pass an error message indicating that the input is invalid.

Note: isdigit() is a method in Python that checks all characters in a given string are numbers or not.

Example:

integer_string = '100'  # This is an integer string
decimal_no = '100.20'  # This is a float string
normal_string = 'FINXTER'  # This is a normal string
if integer_string.isdigit():
    res_1 = int(integer_string)
    print("Converting integer string to integer: ", res_1)
if decimal_no.isdigit():
    res_2 = int(decimal_no)
    print("Converting Decimal String to integer: ", res_2)
if normal_string.isdigit():
    res_3 = int(normal_string)
    print("Converting string to integer: ", res_3)

Output:

Converting integer string to integer:  100

Method 2: Using try and except

When it comes to exceptions, then try and except works like a magic wand. Here’s how you can use them to eliminate the variables which cannot be converted to integers.

Example:

integer_string = '100'  # This is an integer string
decimal_no = '100.20'  # This is a float string
normal_string = 'FINXTER'  # This is a normal string
try:
    # Converting integer string to integer
    res_1 = int(integer_string)
    print(res_1)
    # Converting Decimal String to integer
    res_2 = int(decimal_no)
    print(res_2)
    # Converting string to integer
    res_3 = int(normal_string)
    print(res_3)
except:
    print("Variables that weren't displayed cannot be converted to Integers!")

Output:

100
Variables that weren't displayed cannot be converted to Integers!

Explanation: In the above snippet, the integer string is converted to an integer, but as soon as Python tries to convert the other variables to integers, it encounters a ValueError. This error can then be handled within the except block as shown above.

Method 3: Converting Float Strings to Integers

Well, we saw how we can only convert the integer strings to integers using int(). But what if you want to convert a floating point to an integer. Is there a way to do so? Yes! there is a way. One way to do this is to first, you first need to convert the float string to a floating point value using the float() method and then convert it again to int().

To understand the above procedure let us have a look at the following example:

Example:

decimal_no = '100.20'  # This is a float string
# float string --> float value --> integer
res_2 = int(float(decimal_no))
print("String: ", decimal_no, "---->Type:", type(decimal_no))
print("Float Value: ", float(decimal_no), "---->Type:", type(float(decimal_no)))
print("Integer Value: ", res_2, "---->Type:", type(res_2))

Output:

String:  100.20 ---->Type: <class 'str'>
Float Value:  100.2 ---->Type: <class 'float'>
Integer Value:  100 ---->Type: <class 'int'>

Method 4: Using The Regex Superpower

Let’s say that you have string that has characters as well as digits/integers. Now, you need to extract the digits only. How will we do that? To deal with such a situation you can use the regex module. Let’s have a look at an example that emulates this situation:

Example:

import re

txt = "Extract 100 , 100.45 and 10000 from this string"
res = [int(float(s)) for s in re.findall(r'-?\d+\.?\d*', txt)]
for val in res:
    print(val)

Output:

100
100
10000

Highly Recommended Tutorials if you want to solve problems like this:

In case you are not very supportive of the re library, especially because you find it difficult to get a strong grip on this concept (just like me in the beginning), here’s THE TUTORIAL for you to become a regex master. ?

Conclusion

We learned how to solve the ValueError: invalid literal for int() with base 10 in this article. I hope this discussion you in your coding journey. Please subscribe and stay tuned for more interesting articles!


Google, Facebook, and Amazon engineers are regular expression masters. If you want to become one as well, check out our new book: The Smartest Way to Learn Python Regex (Amazon Kindle/Print, opens in new tab).