In this tutorial, you’ll see 2 ways in which to convert string to the whole number in python.
As we all know we have a tendency to don’t need to declare the datatype whereas declaring variables in Python. As python can assign a knowledge type in line with our data hold on within the variable.
however once we’re operating with graphical user interface (graphical user interface) then the worth fetched from a textbox are a string by default and or we’re taking value from user victimization raw_input() methodology (in Python two.x) and input() methodology (in Python three.x),
then that price will be a string by default. to alter that string into an int sort variable, we will use 2 totally different strategies as given below.
Let’s say our program is:
number1 = input("enter number 1:")
number2 = input("enter number 2:")
sum = number1 + number2
print("sum = " + sum)
Output:
enter number 1: 40
enter number 2: 50
sum = 4050
As we will see in higher than program the input() methodology returns a string that’s why the result holds on in total is 4050 (concatenation of 2 strings) rather than ninety.
to induce the addition of number1 and number2 we’ve to convert each the numbers into an int.
Python Convert String to int
Method 1: victimization int()
number1 = input("enter number 1:")
number2 = input("enter number 2:")
sum = int(number1) + int(number2)
print("sum = " , sum)
Output
enter number 1: 40
enter number 2: 50
sum = 90
In higher than the program we’re victimization int() methodology to convert string to int. we will conjointly use float() methodology to convert it into a float variable.
On alternative hand, to convert all the string things in an exceedingly list into int we will use int() methodology as follows.
list1 = ['1', '2', '3', '4', '5', '6']
print(list1)
list2 = [int(x) for x in list1]
print(list2)
Output
[‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’]
[1, 2, 3, 4, 5, 6]
Method 2: Using Decimal()
import decimal
number1 = input("enter number 1:")
number2 = input("enter number 2:")
sum = decimal.Decimal(number1) + decimal.Decimal(number2)
print("sum = " , sum)
Output:
enter number 1: 40
enter number 2: 50
sum = 90
Decimal() methodology provides bound strategies to perform quicker decimal floating purpose arithmetic victimization the module decimal like sqrt() method or exp() method however as still, we will use it to convert a string to int in python.
If you’ve any downside associated with higher than the article, allow us to apprehend by commenting below.