itoa -- oops.
Alex
alex at somewhere.round.here
Mon Mar 13 19:36:41 EST 2000
> I'm not aware of one, but it's easy to roll your own...
That wasn't really safe. You could get into infinite loops with
non-integer or negative inputs. This version should cope with that:
import string, types
def itoa (n, base = 2):
if type (n) != types.IntType:
raise TypeError, 'First arg should be an integer'
if (type (base) != types.IntType) or (base <= 1):
raise TypeError, 'Second arg should be an integer greater than 1'
output = []
pos_n = abs (n)
while pos_n:
lowest_digit = pos_n % base
output.append (str (lowest_digit))
pos_n = (pos_n - lowest_digit) / base
output.reverse ()
if n < 0:
output.insert (0, '-')
return string.join (output, '')
if __name__ == '__main__':
assert itoa (16) == '10000'
assert itoa (17) == '10001'
assert itoa (-17) == '-' + itoa (17)
Alex.
More information about the Python-list
mailing list