Python Convert String to Int


Convert String to Int

To convert given value of string to integer in Python, call the int() built-in function. Pass the string as argument to int() and it returns an integer value.

int(s) #s is given string

As integer can be represented using different base values, and if the given string is a representation of an integer in a specific base value, we can pass both the string and base as arguments to int() function.

#s is given string
#default base value is 10
int(s, base=10)

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

Video Tutorial

https://youtu.be/1ThkC-BBeoc?si=itHKIFW9ZxT2M_r7

Examples

1. Convert string to integer (with default base value)

In this example, we will take a string in a, convert it to int using int().

Python Program

#take a string
a = '125'
print('Input', a, type(a), sep='\n')

#convert string to int
output = int(a)
print('\nOutput', output, type(output), sep='\n')

Output

Input
125
<class 'str'>

Output
125
<class 'int'>

2. Convert binary string to integer

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

Python Program

#take a binary string
a = '10111010'
print('Input', a, type(a), sep='\n')

#convert binary string to int
output = int(a, base=2)
print('\nOutput', output, type(output), sep='\n')

Output

Input
10111010
<class 'str'>

Output
186
<class 'int'>

3. Convert hex string to integer

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

Python Program

#take a hex string
a = 'AB96210F'
print('Input', a, type(a), sep='\n')

#convert hex string to int
output = int(a, base=16)
print('\nOutput', output, type(output), sep='\n')

Output

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

4. Convert octal string to integer

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

Python Program

#take a hex string
a = '136'
print('Input', a, type(a), sep='\n')

#convert octal string to int
output = int(a, base=8)
print('\nOutput', output, type(output), sep='\n')

Output

Input
136
<class 'str'>

Output
94
<class 'int'>

Summary

In this tutorial of Python Examples, we learned to convert a string value to an integer value, with the help of int() function.