how to add new print %b format to python?

Brian Kelley bkelley at wi.mit.edu
Tue Apr 27 10:29:21 EDT 2004


John Roth wrote:

> "Rusty Shackleford" <rs at overlook.homelinux.net> wrote in message
> news:slrnc8q9qp.htc.rs at frank.overlook.homelinux.net...
> 
>>I have a Summer in front of me without any school, and I'd like to add a
>>new format for python print strings that will show any number in a
>>binary representation.  For example:
>>
>>
>>>>>'%b' % 3
>>
>>11
>>
>>>>>'%b' % 5
>>
>>101

For some implementation PEP discussion ideas, I like this format, but 
there are additional complexities such as what is

'%b' % -1 ?

This might just be a binary string equivalent to the current machine 
bits.  But what about long integers?

'%b' % (-1L)

This is technically an infinite string of ones.

Perhaps a useful solution is when printing out negative numbers, the 
user must supply the padding.

so
 >> '%b' % (-1)

raise a ValueError or some such and

Traceback (most recent call last):
   File "<stdin>", line 1, in ?
ValueError: Binary format %b for negative numbers must have bit length
             specified

and

 >> '%32b' % (-1L)
11111111111111111111111111111111

Now for the source, you want to look at stringobject.c and in particular 
the PyString_Format function.  You can find the cvs version here:

http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Objects/stringobject.c?view=markup

Note that you can make a test case by subclass string and the __mod__ 
function.  This might actually be harder though since you will have to 
figure out which argument is supposed to belong to the %b formatter.

from types import StringType

class mystring(StringType):
     def __mod__(self, *k, **kw):
         return StringType.__mod__(self, *k, **kw)

Good Luck








More information about the Python-list mailing list