formatted output

Guido.van.Rossum@cwi.nl
Mon, 08 Mar 1993 15:00:52 +0100

As you all know, formatted output isn't currently among Python's
strong points. Here's an idea to fix it. Comments, please!

- The binary operator '%' is overloaded with a new meaning: if its
left argument is a string, the right argument can be any value, and
the result is a string.

- The outcome of "s % v" is informally defined as the string resulting
from "sprintf(buf, s, v)" in C.

- The outcome of "s % (v1, v2, ...)" is similarly defined as the
result of "sprintf(buf, s, v1, v2, ...)".

The net effect is that you can do things like

>>> print '/%6d/%6g/%-6s/' % (300, 3.14, 'x')
/ 300/ 3.14/x /
>>>

But also

>>> s = '/%6d/%6g/%-6s/' % (300, 3.14, 'x')
>>> print s
'/ 300/ 3.14/x /'
>>>

Complete error checking will of course ensure that mismatches between
the format and the supplied values will raise exceptions rather than
dump core or yield garbage. Possibly the range of values accepted by
certain format codes will be richer than for C, e.g. %f and %g will
work with integers, and some format codes will be identical, e.g. %hd,
%d and %ld should make no difference. Arbitrary values can be
formatted using '%s' % `value`. (That's reverse quotes around value.)

I hope this concise description conveys my ideas (which are less than
half an hour old at the moment I am writing this) sufficiently.
Please send in your suggestions for alternatives!

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>

PS. I'm sorry for not responding to some earlier messages, e.g. about
program structure -- the issues raised there are certainly
interesting, I'm just incredibly busy...