Table of Contents
In this post, we will see about Valueerror: Invalid literal for int() with base 10
.
You will see this error, when you are trying to convert string to int using int()
function. If you provide invalid string input to int()
function, you will get this error.
Here is the slider to understand it better.
[smartslider3 slider=5]
Let’s see this with the help of example.
1 2 3 4 5 |
str1 ='java2blog' strInt = int(str1) print(strInt) |
Output:
1 2 3 4 5 6 7 8 9 10 11 |
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-13-787afdfc64da> in <module> 1 str1 ='java2blog' ----> 2 strInt = int(str1) 3 print(strInt) ValueError: invalid literal for int() with base 10: 'java2blog' </module></ipython-input-13-787afdfc64da> |
Obviously, you can not convert 'java2blog'
to int type, hence getting Valueerror: Invalid literal for int() with base 10
.
Let’s see another example.
1 2 3 4 5 |
str1 ='30' strInt = int(str1) print(strInt) |
Output:
As you can see, when we put valid int value, it worked fine.
Float number
You can directly use int()
function to convert float number to int.
1 2 3 4 5 |
float1 =30.23 int1 = int(str1) print(int1) |
Output:
If you try to convert a float string
to int
using int()
function, you will get Valueerror: Invalid literal for int() with base 10
.
Let’s see with the help of example.
1 2 3 4 5 |
str1 ='30.23' strInt = int(str1) print(strInt) |
Output:
1 2 3 4 5 6 7 8 9 10 11 |
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-15-24bc2bd52b89> in <module> 1 str1 ='30.23' ----> 2 strInt = int(str1) 3 print(strInt) ValueError: invalid literal for int() with base 10: '30.23' </module></ipython-input-15-24bc2bd52b89> |
If you want to convert float string '30.23'
to int, you need to first use float()
function and then int()
function as below.
1 2 3 4 5 |
str1 ='30.23' strInt = int(float(str1)) print(strInt) |
Output:
As you can see, we are able to successfully convert 30.23
to int.
Use try-except
You can use try-except
to handle this error.
Let’s see this with the help of example.
1 2 3 4 5 6 7 8 |
str1 ='java2blog' try: strInt1 = int(str1) print(strInt1) except: print('Can not convert',str1,"to int") |
Output:
That’s all about Valueerror: Invalid literal for int() with base 10.