views:

438

answers:

3

python allows conversions from string to integer using any base in the range [2,36] using:

int(string,base)

im looking for an elegant inverse function that takes an integer and a base and returns a string

for example

>>> str_base(224,15)
'ee'

i have the following solution:

def digit_to_char(digit):
    if digit < 10: return chr(ord('0') + digit)
    else: return chr(ord('a') + digit - 10)

def str_base(number,base):
    if number < 0:
        return '-' + str_base(-number,base)
    else:
        (d,m) = divmod(number,base)
        if d:
            return str_base(d,base) + digit_to_char(m)
        else:
            return digit_to_char(m)

note: digit_to_char() works for bases <= 169 arbitrarily using ascii characters after 'z' as digits for bases above 36

is there a python builtin, library function, or a more elegant inverse function of int(string,base) ?

A: 

A little googling brings this. One of the comments talks about Python builtin functions:

int(x [,base]) converts x to an integer
long(x [,base]) converts x to a long integer
float(x) converts x to a floating-point number
complex(real [,imag]) creates a complex number
chr(x) converts an integer to a character
unichr(x) converts an integer to a Unicode character
ord(c) converts a character to its integer value
hex(x) converts an integer to a hexadecimal string
oct(x) converts an integer to an octal string

But none of them seems right. I guess you just need to code your own function. There is sample code in the link.

gruszczy
+1  A: 

This thread has some example implementations.

unwind
+1  A: 

digit_to_char could be implemented like this:

def digit_to_char(digit):
    return (string.digits + string.lowercase)[digit]
Wim