String formatters with variable argument length

John Machin sjmachin at lexicon.net
Thu Nov 30 19:47:21 EST 2006


John Machin wrote:
> Fredrik Tolf wrote:
> > I've been trying to get the string formatting operator (%) to work with
> > more arguments than the format string requires, but I can find no way to
> > do that. For example:
> >
> > >>> "%i" % 10
> > '10'
> > >>> "i" % 10
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in ?
> > TypeError: not all arguments converted during string formatting
> >
> > The thing is, I want to get format strings from the user, and I don't
> > want to require the user to consume all the arguments. docs.python.org
> > doesn't seem to have any clues on how to achieve this, and I can't think
> > of what to google for.
> >
> > Could it be as I fear, that it is impossible?
> >
>
> Three approaches spring to mind. In descending order of my preference:
>
> (a) don't do that
>
> (b) parse the format string, counting the number of args required. If
> the user has supplied more, throw them away.
>
> (c) wrap your execution of format_string % args in a try/except
> bracket. If you get a TypeError with that message [not guaranteed to
> remain constant in the future], throw away the last arg and go around
> again.
>
> As a matter of curiosity, why don't you want the user to consume all
> the arguments? Don't they get even a teensy-weensy warning message? Are
> you writing a Perl interpreter in Python?
>

Another approach: instead of the "%s %.2f %.5f%%" style, give the users
a list of names of each possible arg so that they can do e.g.

"The rate for %(name)s is %(rate).5f%%"
or
"Amount borrowed: $%(amount).2f; borrower: %(name)s"

HTH,
John




More information about the Python-list mailing list