itoa (WAS: Re: %a format)

Steven Bethard steven.bethard at gmail.com
Wed Sep 8 20:38:04 EDT 2004


> class Bits(int):
>    def __sprintf__(self, flags, precision, conversion):
>       if conversion == 'b':
>          # return a binary string
>          return itoa(self, 2) # Why isn't this a standard function?
>       else:
>          return NotImplemented

Well, I'm guessing itoa isn't a standard function because it's not that 
commonly used...  Not that I'm claiming to have written the widest variety of 
Python code, but I've never needed it.

It is available though through a relatively short sequence of builtins though:

>>> def itoa(i, base):
...     return str(int(str(i), base))
...
>>> itoa(100, 2)
'4'

A little roundabout, but it does do the trick.

Steve




More information about the Python-list mailing list