Inverse of int(s, base)?
Dan Bishop
danb_83 at yahoo.com
Tue May 11 01:13:25 EDT 2004
olli at secnetix.de wrote in message news:<2gac73Fk1ooU1 at uni-berlin.de>...
> Hi,
>
> Is there an inverse function of int(s, base) where base
> can be any number up to 36?
Yes, but for some reason it's not in the Python standard library.
...
> PS: This is what I'm using right now.
>
> import string
> str_digits = string.digits + string.ascii_lowercase
>
> def str_base (x, base):
> result = ""
> while x:
> result = str_digits[x % base] + result
> x /= base
The above line should be "x //= base", so it works under -Qnew.
> return result or "0"
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):
if n == 0:
return '0'
isNegative = n < 0
if isNegative:
n = -n
result = []
while n > 0:
n, lastDigit = divmod(n, base)
result.append(str_digits[lastDigit])
if isNegative:
result.append('-')
result.reverse()
return ''.join(result)
More information about the Python-list
mailing list