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.

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')
Run Code Copy

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')
Run Code Copy

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')
Run Code Copy

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')
Run Code Copy

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.

Related Tutorials

Code copied to clipboard successfully 👍