print format for binary representation

Dan Bishop danb_83 at yahoo.com
Tue Jan 27 21:31:38 CET 2004


rimbalaya at yahoo.com (Rim) wrote in message news:<6f03c4a5.0401270700.713a73aa at posting.google.com>...
> Hi,
> 
> >>> print '%x' % 54
>  36
> >>> print '%b' % 54
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: unsupported format character 'b' (0x62) at index 1
> >>>
> 
> No formating string for binary? There %x for hex. Would %b make sense
> for bin? Is this worth a PEP?

Yes, it would.  No, it isn't.

What we really need is an inverse to the int constructor.  Something like:

def itoa(x, base=10):
   isNegative = x < 0
   if isNegative:
      x = -x
   digits = []
   while x > 0:
      x, lastDigit = divmod(x, base)
      digits.append('0123456789abcdefghijklmnopqrstuvwxyz'[lastDigit])
   if isNegative:
      digits.append('-')
   digits.reverse()
   return ''.join(digits)

> How do I get 00110110 printed instead of the traceback?

print itoa(54, 2).zfill(8)



More information about the Python-list mailing list