how to convert base in python code example

Example 1: python convert base

# add as many different characters as you want
alpha = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"


def convert(num, base=2):
    assert base <= len(alpha), f"Unable to convert to base {base}"
    converted = ""
    while num > 0:
        converted += alpha[num % base]
        num //= base

    if len(converted) == 0:
        return "0"
    return converted[::-1]
  

print(convert(15, 8))  # 17

Example 2: base conversion python

alpha = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"


def convert(num, base=2):
    assert base <= len(alpha), f"Unable to convert to base {base}"
    converted = ""
    while num > 0:
        converted += alpha[num % base]
        num //= base

    if len(converted) == 0:
        return "0"
    return converted[::-1]
  

print(convert(15, 8))  # 17