Convert String to Int Base in Python

The int() function in Python converts a string to an integer. But this function has the second default parameter: base. The base can be between 2 (you need to have at least 2 different values) and 36 (numbers + letters). The default value is 10.

Both examples return the same result:

print(int('156'))
print(int('156', 10))

Result:

156
156

This means, by how many elements the value will be represented. Look at the following table to see how it works.

 Base available numbers and letters
 2 01
3012
40123
501234
6012345
70123456
801234567
9012345678
100123456789
160123456789abcdef
200123456789abcdefghij
360123456789abcdefghijklmnopqrstuwvxyz

Now, take a look at the following examples:

print(int('10011100001111', 2))
print(int('111201100', 3))
print(int('2130033', 4))
print(int('304444', 5))
print(int('114143', 6))
print(int('41103', 7))
print(int('23417', 8))
print(int('14640', 9))
print(int('9999', 10))
print(int('270f', 16))
print(int('14jj', 20))
print(int('7pr', 36))

All of these lines return the same result, which is 9999.

If you want to convert an integer to binary (2), octal (8), hex (16) or any other base between 2 and 36, you can use the following function.

def dec_to_base(number, base, characters='0123456789abcdefghijklmnopqrstuvwxyz'):
    if base < 2 or base > len(characters):
        raise ValueError("Base value must be between 2 and 36")

    if number == 0:
        return '0'

    if number < 0:
        sign = '-'
        number = -number
    else:
        sign = ''

    result = ''
    while number:
        result = characters[number % (base)] + result
        number //= base

    return sign + result

Now use the following code to display values.

print(dec_to_base(9999, 2))
print(dec_to_base(9999, 3))
print(dec_to_base(9999, 4))
print(dec_to_base(9999, 5))
print(dec_to_base(9999, 6))
print(dec_to_base(9999, 7))
print(dec_to_base(9999, 8))
print(dec_to_base(9999, 9))
print(dec_to_base(9999, 10))
print(dec_to_base(9999, 16))
print(dec_to_base(9999, 20))
print(dec_to_base(9999, 36))

It will return the following result.

10011100001111
111201100
2130033
304444
114143
41103
23417
14640
9999
270f
14jj
7pr