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(binary(4096))
Pádraig.