My Coding > Programming language > Python > Exercise > Python: How to convert integer to string in any base

Python: How to convert integer to string in any base

int to str with base < 36

It is very easy to convert integet to a string with any base, but this example will only work with base below an alphabet length. If you need to have bigger basem it is possible to use bigger alphabet, or use list structure to keep every digit separately


def convert(n, b=10):
    alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    if n == 0: return '0'
    res = ''
    while n:
        res += alphabet[int(n % b)]
        n //= b
    return res[::-1]

print(convert(169345, 2))  # 101001010110000001
print(convert(169345, 8))  # 512601
print(convert(169345, 16)) # 29581
print(convert(169345, 33)) # 4NGM

int to str with base >= 36

If the base is bigger than alphabet, then we need to have other way to store and display it. We can use similar system which used for time representation (base = 60)


def convert(n, b=10):
    if n == 0: return '0'
    res = []
    while n:
        res.append(str(int(n % b)))
        n //= b
    return res[::-1]

print(':'.join(convert(169345, 2)))  # 1:0:1:0:0:1:0:1:0:1:1:0:0:0:0:0:0:1
print(':'.join(convert(169345, 8)))  # 5:1:2:6:0:1
print(':'.join(convert(169345, 16))) # 2:9:5:8:1
print(':'.join(convert(169345, 33))) # 4:23:16:22
print(':'.join(convert(169345, 60))) # 47:2:25


Published: 2021-11-07 02:55:23

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.