Convert String to Integer
To convert a String to Integer in Python, use int() builtin function. int() function can take a string as argument and return an int equivalent of the given argument.
The syntax to convert a string x to integer is
int(x)
Examples
In the following example, we take a string in variable x
, and convert it into integer using int()
function. We shall print the integer output
to console, and to confirm the datatype of the variable output
, we shall print its datatype as well using type().
Python Program
x = '125'
output = int(x)
print(output)
print(type(output))
Output
125
<class 'int'>
Negative Scenarios
If there are any invalid characters for an integer, then int() function raises ValueError as shown in the following.
The character 'a'
is not valid to be in an integer. Therefore, trying to convert '125a'
to integer by int()
function raises ValueError.
Python Program
x = '125a'
output = int(x)
print(output)
print(type(output))
Output #1
Traceback (most recent call last):
File "/Users/tutorialkart/python/example.py", line 2, in <module>
output = int(x)
ValueError: invalid literal for int() with base 10: '125a'
To handle this error, we may use try-except around our code.
Python Program
x = '125a'
try:
output = int(x)
print(output)
print(type(output))
except ValueError:
print('Cannot convert to integer')
Output
Cannot convert to integer
Conclusion
In this Python Tutorial, we learned how to convert a string into an integer, and also handle if the string cannot be converted to a valid integer.