pythonbase36

Python: converting base 10 to base 36


I'm trying to convert decimal to base 36 (...8,9,a,b,c...x,y,z,10,11...) but when I run my code I get a bunch of floats instead of integers.

def trc(n):
    if (n < 0): print(0, end='')
    elif (n<=1): print(n, end='')
    else:
        trc( n / 36 )
        x =(n%36)
        if (x < 10): print(x, end='')
        else: print(chr(x+87), end='')

I based this code off of this.


Solution

  • In Python 3, the / operator does floating point division, even when both arguments are integers. This is a change from Python 2, where dividing two integers would discard the fractional part.

    You can explicitly request integer division by using the // operator. The result will be rounded towards negative infinity. Or, since you're also calculating the modulus, you could use divmod to get them both at the same time:

    else:
        n, x = divmod(n, 36)
        trc(n)
        if x < 10: # ...