a=0100; print a ; 64 how to reverse this?

Duncan Booth duncan.booth at invalid.invalid
Tue Jul 17 15:53:09 CEST 2007


John Machin <sjmachin at lexicon.net> wrote:

> Here's a sketch; I'll leave you to fill in the details -- you may wish
> to guard against interesting input like b < 2.
> 
>>>> def anybase(n, b, digits='0123456789abcdef'):
> ...    tmp = []
> ...    while n:
> ...       n, d = divmod(n, b)
> ...       tmp.append(digits[d])
> ...    return ''.join(reversed(tmp))
> ...

Nice. Here's a one-line version based on your code (with added check for 
negative n):

def anybase(n, b, digits='0123456789abcdef'):
	return ('-'+anybase(-n,b) if n < 0
		else '0' if n==0
		else ''.join([digits[d] for (n,d) in iter(lambda:divmod(n,b),
(0,0))])[::-1])




More information about the Python-list mailing list