473,581 Members | 2,304 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to add new print %b format to python?

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

You get the idea. I've written functions that return strings, so that
part is done, but where do I go to tinker with the python interpreter to
add this new format?

Please don't argue with me about whether this is an advisable goal in
itself -- I'm using it as a method to learn about the internals of the
python language.
--
My public key:
gpg --recv-keys --keyserver www.mandrakesecure.net 0x8D10BFD5
Jul 18 '05 #1
4 2770
P
Rusty Shackleford wrote:
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

You get the idea. I've written functions that return strings, so that
part is done, but where do I go to tinker with the python interpreter to
add this new format?

Please don't argue with me about whether this is an advisable goal in
itself -- I'm using it as a method to learn about the internals of the
python language.


I don't think this will be accepted as the
format args are really a lowest common denominator
across all systems. For e.g. on linux you can use
the ' modifier to print numbers in locale format
(and example for mine is 1,234).

Also %b is already used by userspace utils in linux, from the docs:

In addition to the standard printf(1)
formats, %b causes printf to expand backslash escape
sequences in the corresponding argument, and %q causes
printf to output the corresponding argument in a format
that can be reused as shell input.

Anyway it's easy to get a binary representation
and I can't remember the last time I needed one?
Something like this should work:

binary = lambda n: n>0 and binary(n>>1)+[str(n&1)] or []
''.join(map(bin ary(4096))

Pádraig.
Jul 18 '05 #2

<P@draigBrady.c om> wrote in message news:40******** ******@draigBra dy.com...
Rusty Shackleford wrote:
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

You get the idea. I've written functions that return strings, so that
part is done, but where do I go to tinker with the python interpreter to
add this new format?

Please don't argue with me about whether this is an advisable goal in
itself -- I'm using it as a method to learn about the internals of the
python language.


I don't think this will be accepted as the
format args are really a lowest common denominator
across all systems. For e.g. on linux you can use
the ' modifier to print numbers in locale format
(and example for mine is 1,234).


I don't believe this is the case. I think the % operator
does not use the C library's sprintf function., but I could
be wrong.

[snip]

The rest of this is equally off base - he explicitly said he
was not interested in ***whether*** he should do it, but
only in *** where to look *** to find out how to do it
as a summer programming exercise in the python core.

John Roth
Pádraig.

Jul 18 '05 #3
"Rusty Shackleford" <rs@overlook.ho melinux.net> wrote in message
news:sl******** *******@frank.o verlook.homelin ux.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

You get the idea. I've written functions that return strings, so that
part is done, but where do I go to tinker with the python interpreter to
add this new format?

Please don't argue with me about whether this is an advisable goal in
itself -- I'm using it as a method to learn about the internals of the
python language.


Well, if I was familiar with the internals, I'd start with the code
that implements the string object, since it's simply an overload of
the '%' operator. Sorry I can't help you with a module name, though.

To actually get it added to the core, you need to write a PEP and
champion it through the process. Writing a reference implementation
and the documentation is also a necessity. There's a PEP that
explains the documentation standards for Python C language code;
if your patch follows that you've improved your chances by some
significant amount.

John Roth

Jul 18 '05 #4
John Roth wrote:
"Rusty Shackleford" <rs@overlook.ho melinux.net> wrote in message
news:sl******** *******@frank.o verlook.homelin ux.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)

111111111111111 111111111111111 11

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.p....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(String Type):
def __mod__(self, *k, **kw):
return StringType.__mo d__(self, *k, **kw)

Good Luck

Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

30
4144
by: Martin Bless | last post by:
Why can't we have an additional 'print' statement, that behaves exactly like 'print' but doesn't insert that damn blank between two arguments? Could be called 'printn' or 'prin1' or 'prinn' anything similar you like. Would make my life so much easier. Often I start with a nice and short print statement, then there happen to be more...
3
6350
by: Paul Watson | last post by:
It is clear that just using 'print' with variable names is relatively uncontrollable. However, I thought that using a format string would reign the problem in and give the desired output. Must I resort to sys.stdout.write() to control output? $ python Python 2.4.1 (#1, Jul 19 2005, 14:16:43) on linux2 Type "help", "copyright",...
3
2103
by: James J. Besemer | last post by:
I would like to champion a proposed enhancement to Python. I describe the basic idea below, in order to gage community interest. Right now, it's only an idea, and I'm sure there's room for improvement. And of course it's possible there's some serious "gotcha" I've overlooked. Thus I welcome any and all comments. If there's some...
4
3488
by: PengYu.UT | last post by:
Suppose I have a dos format text file. The following python code will print ^M at the end. I'm wondering how to print it in unix format. fh = open(options.filename) for line in fh.readlines() print line, Thanks, Peng
6
1260
by: Why Tea | last post by:
print format % values An optional minimum width of the conversion, specified using one or more digits or an asterisk (*), which means that the width is taken from the next item in values That's from one of O'reilly's books. But there is no example and I couldn't get it to work by trials and errors. Does anyone have a working example? ...
9
2616
by: cniharral | last post by:
Hi, I'm interested in printing out coloured lines of my application and I don't know what to use. Can anybody give me an idea?? Regards. Carlos Niharra López
4
25443
by: mike | last post by:
guys, I've researched python pretty much but still have no idea how to print out each single character from a string in HEX format? Hope someone can give me some hints. Thanks a lot. e.g. ###here is a string a='01234'
2
2316
by: CC | last post by:
Hi: I've conjured up the idea of building a hex line editor as a first real Python programming exercise. To begin figuring out how to display a line of data as two-digit hex bytes, I created a hunk of data then printed it: ln = '\x00\x01\xFF 456789abcdef' for i in range(0,15):
5
2365
by: sniipe | last post by:
Hi, I have a problem with unicode string in Pylons templates(Mako). I will print first char from my string encoded in UTF-8 and urllib.quote(), for example string '£ukasz': ${urllib.unquote(c.user.firstName).encode('latin-1')} and I received this information:
0
7868
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7792
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8304
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8175
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6553
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5674
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5364
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3827
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1403
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.