How To Convert string to integer in Python

Created
Modified

Using int Built-in Function

Return an integer object constructed from a number or string x, or return 0 if no arguments are given.

#!/usr/bin/python3
# -*- coding: utf8 -*-

s = "100"

# class int(x, base=10)
i = int(s)
print(i)
print(type(i))
100
<class 'int'>

Python different number data types: long() float() complex().

Convert with different bases

If the String you want to convert into int belongs to a different number base other than base 10, you can specify that base for that conversion.

See the following example:

#!/usr/bin/python3
# -*- coding: utf8 -*-

s = "101010"

i = int(s)
print(i)

# base binary
i = int(s, 2)
print(i)
print(type(i))

# a binary string
print(bin(42))
101010
42
<class 'int'>
0b101010

Python error: invalid literal for int() with base 10.

#!/usr/bin/python3
# -*- coding: utf8 -*-

s = "a1f"

i = int(s)
print(i)
ValueError: invalid literal for int() with base 10: 'a1f'

a hexadecimal string,

#!/usr/bin/python3
# -*- coding: utf8 -*-

s = "a1f"

# base hexadecimal
i = int(s, 16)
print(i)
print(type(i))

# a hexadecimal string
print(hex(2591))
2591
<class 'int'>
0xa1f

Related Tags