Python program to convert a string to an integer

How to convert a string to an integer in python :

In this tutorial, we will learn how to convert a string variable to an integer or a float in python programming language. Python automatically assign the data type according to the data stored in the variable. Sometimes we have to store a value as string in a variable and then we need to calculate the sum of this variable with other numeric variables. In that case, we need to convert the string to an integer value (if we know that it will be integer always). For example, take a look at the below program :

first_number = "1"
second_number = 2
print(first_number+second_number)

It will throw one error like this :

TypeError: cannot concatenate 'str' and 'int' objects

So, to fix this error , we will have to convert the string first_number to an integer variable.

Python program to convert a string to an integer :

The conversion is simpler than you think. Python has one built-in function called int() to make this conversion. Let’s take a look :

first_number = "1"
second_number = 2
print(int(first_number) + second_number)

It will print 3 as the output.
But, suppose the string first_number holds a different value than a number like below :

first_number = "1@"
second_number = 2
print(int(first_number) + second_number)

It will throw one error :

ValueError: invalid literal for int() with base 10: '1@'

So, the best way to handle this is to use one try-catch block like below :

first_number = "1@"
second_number = 2
try:
    print(int(first_number) + second_number)
except Exception:
    print("Conversion Error !!")

It will print the exception error.

Leave a Reply