Python convert base 10 to base 6

One direction is clear:

>>> int['42', 6]
26

The other way - convert a number to a base 6 representation - is trickier. There seems to be no way to do it with built-in functions and without a loop.

So one could do something like

def str_base[val, base]:
    res = ''
    while val > 0:
        res = str[val % base] + res
        # val /= base # only valid for Py2
        val //= base # for getting integer division
    if res: return res
    return '0'

This gives e.g.:

>>> str_base[7,6]
'11'

Till now, it only works with bases 0: dig = int[num%base] if dig 0: digit = n%k digits. append[digit] n /= k n_k = reversed[digits] ... .

n = sum of i from 0 to infinity of c_i*[k^i] where 0

Chủ Đề