Convert string to int Python
In this post, you will learn how to convert a string to an integer in Python programming programming.
In the development process, we may come to the situation where we need to convert values between types in order to manipulate values in a different way. For example, we receive input from the user in a string format, but the program may need them in integer format. Similar to the Python inbuilt str() method to convert an integer to a string, Python also provides int() method to convert string to integer. It takes a string object as an argument and returns an integer.
Convert string to int using int()
Here is the syntax of int() function in which str is the initial string -
int(str)
Example to convert a string to an integer
In the given example, we have converted string to int using the Python int() method -
x = '100'
# print type of variable
print(type(x))
print("x = ", x)
# convert the variable into int
y = int(x)
# print type of conversion
print(type(y))
print("y = ",y)
Output of the above code -
<class 'str'>
x = 100
<class 'int'>
y = 100
Instead of converting a string to an int, this method also provides a feature to convert one base value to another base value, as follows -
x = '110010'
# print type of variable
print(type(x))
print("x = ", x)
# convert it to base 2
y = int(x, base=2)
# print type of conversion
print(type(y))
print("Base 2 to base 10 = ",y)
# convert it to base 6
print("Base 6 to base 10 = ",int(x, base=6))
# convert it to base 8
print("Base 8 to base 10 = ",int(x, base=8))
Output of the above code -
<class 'str'>
x = 110010
<class 'int'>
Base 2 to base 10 = 50
Base 6 to base 10 = 9078
Base 8 to base 10 = 36872
Related Articles
Convert list to dictionary Python
Convert array to list Python
numpy dot product
glob in Python
Python heap implementation
zip function in Python
Remove last element from list Python
Check if list is empty Python
Remove element from list Python
Python split multiple delimiters
Python loop through list
Python iterate list with index
Python add list to list
Python random choice
Python dict inside list
Remove character from string Python
Python raise keyword