itoa -- oops.

Stuart Reynolds S.I.Reynolds at cs.bham.ac.uk
Tue Mar 14 06:31:55 EST 2000


Alex wrote:
> 
> > 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:

Great. I've included a quick fix to also let it work up to base 36 (10
digits + 26 letters).

> 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 not (2<=base<=36):
        raise TypeError, 'Second arg should be an integer between 2 and
36'

>     output = []
>     pos_n = abs (n)
>     while pos_n:
>         lowest_digit = pos_n % base

        if lowest_digit>=10:
            output.append( chr( ord('a')+lowest_digit-10 ) )
        else:
            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)


    assert itoa(10, 16)  == 'a'
    assert itoa(15, 16)  == 'f'
    assert itoa(16, 16)  == '10'

    assert itoa(255, 16)  == 'ff'
    assert itoa(256, 16)  == '100'
    
    assert itoa(35, 36)  == 'z'
    assert itoa(36, 36)  == '10'
    assert itoa(-35, 36)  == '-z'
    assert itoa(-36, 36)  == '-10'
   

Stuart



More information about the Python-list mailing list