Convert string into int in Python
String
A string is defined as a series of characters, special characters, and numbers. A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation).
Integer
An integer is defined as the collection of numbers that includes all numbers except decimal and fractional parts such as zero, positive numbers, and negative numbers.
String to Integer conversion
The strings can be easily converted into an integer in Python with the help of the int() function. A Python data type of any type is taken by the int function and it will be converted into an integer.
Also, this type of conversion can be performed with the float() keyword.
With int() function
A Python string can easily convert into an integer. If a decimal integer is expressed as a string and then the string needs to just pass to int() function and it returns a decimal integer.
Syntax:
int(string)
Example:
num = '20'
# printing num variable with type
print(type(num))
# num is to be converted into string
converted_num = int(num)
# print converted_num type
print(type(converted_num))
# apply some mathematical operations and check
print(converted_num + 23)
Output:
<class 'str'>
<class 'int'>
43
With float() function
Firstly, we convert string to float and then convert it into an integer.
Syntax:
float(string)
Example:
converting string to float
num = '23.6'
# printing num variable with type
print(type(num))
# convert the num into string
converted_num = float(num)
#print converted_num type
print(type(converted_num))
# apply some mathematical operations and check
print(converted_num + 24.8)
Output:
<class 'str'>
<class 'float'>
48.400000000000006
Example 2:
Converting float to integer
a = '60'
b = '70'
# printing the type of data of a and b
print(type(a))
print(type(b))
# converting (a) using float
a = float(a)
# converting (b) using int
b = int(b)
# calculating sum of a and b
sum = a + b
#Checking the sum
print(sum)
Output:
<class 'str'>
<class 'str'>
130.0