Python Convert String to Int

Convert String to Integer in Python

To convert string to integer in python, you can use the int() class with the string passed as argument to it. As integer can be represented using different base values, you can use int() constructor with both the string and base passed as arguments to it.

In this tutorial, we shall go through some of the example programs that convert a string to integer.

Example 1: String to Int

In this example, we will take a string, print it and its datatype, then convert it to int.

Python Program

a = '125'
print(a, 'is of type:', type(a))

a = int(a)
print(a, 'is of type:', type(a))
Run

Output

125 is of type: <class 'str'>
125 is of type: <class 'int'>

Example 2: Binary String to Int

In this example, we will convert binary representation of a number in string, to integer.

Python Program

a = '10111010'
print(a, 'is of type:', type(a))

a = int(a, base=2)
print(a, 'is of type:', type(a))
Run

Output

10111010 is of type: <class 'str'>
186 is of type: <class 'int'>

Example 3: Hex String to Int

In this example, we will convert hexadecimal representation of a number in string, to integer.

Python Program

a = 'AB96210F'
print(a, 'is of type:', type(a))

a = int(a, base=16)
print(a, 'is of type:', type(a))
Run

Output

AB96210F is of type: <class 'str'>
2878742799 is of type: <class 'int'>

Example 4: Octal String to Int

In this example, we will convert Octal representation of a number in string, to integer.

Python Program

a = '13'
print(a, 'is of type:', type(a))

a = int(a, base=8)
print(a, 'is of type:', type(a))
Run

Output

13 is of type: <class 'str'>
11 is of type: <class 'int'>

Summary

In this tutorial of Python Examples, we converted/typecasted variable of string datatype to variable of int datatype, with the help of int() constructor.