random guy - 5 months ago 43

Python Question

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) ?

Answer

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 think `if foo: return`

is very clear, and doesn't need an `else`

after it to make it clear it's a separate branch.

```
def digit_to_char(digit):
if digit < 10:
return str(digit)
return chr(ord('a') + digit - 10)
def str_base(number,base):
if number < 0:
return '-' + str_base(-number, base)
(d, m) = divmod(number, base)
if d > 0:
return str_base(d, base) + digit_to_char(m)
return digit_to_char(m)
```

I simplified the 0-9 case in `digit_to_char()`

, I think `str()`

is clearer than the `chr(ord())`

construct. To maximize the symmetry with the `>= 10`

case an `ord()`

could be factored out, but I didn't bother since it would add a line and brevity felt better. :)