Inverse of int(s, base)?
Paul Rubin
http
Tue May 11 04:00:48 EDT 2004
danb_83 at yahoo.com (Dan Bishop) writes:
> > while x:
> > result = str_digits[x % base] + result
> > x /= base
>
> The above line should be "x //= base", so it works under -Qnew.
Or just say:
x, r = divmod(x, base)
result = result + str_digits[r]
> That works (for positive integers), but it might be more efficient to
> not create a new string each time through the loop. An alternative is:
>
> def str_base(n, base=10):
...
Similarly:
def str_base(n, base=10):
results = []
sign,n = ('','-')[n < 0], abs(n)
while n:
n, r = divmod(n, base)
results.append(str_digits[r])
results.reverse()
return sign + ''.join(results)
More information about the Python-list
mailing list