Python allows conversions from string to integer using any base in the range [2,36] using:
int(string,base)
I am 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 came up with 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 built‑in, library function, or a more elegant inverse function of int(string,base)?
This thread has some example implementations.
Actually I think your solution looks rather nice, it’s even recursive which is somehow pleasing here.
I’d still simplify it to remove the
else, but that’s probably a personal style thing. I thinkif foo: returnis very clear, and doesn’t need anelseafter it to make it clear it’s a separate branch.I simplified the 0-9 case in
digit_to_char(), I thinkstr()is clearer than thechr(ord())construct. To maximize the symmetry with the>= 10case anord()could be factored out, but I didn’t bother since it would add a line and brevity felt better. 🙂