String formatters with variable argument length
Fredrik Tolf
fredrik at dolda2000.com
Thu Nov 30 19:50:44 EST 2006
On Thu, 2006-11-30 at 16:26 -0800, John Machin wrote:
> Fredrik Tolf wrote:
[...]
> > 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.
>
> Three approaches spring to mind. In descending order of my preference:
>
> (a) don't do that
It would be a possibility, since all current uses actually do have the
right number of parameters. I would just like to keep the option
available.
> (b) parse the format string, counting the number of args required. If
> the user has supplied more, throw them away.
I was thinking of that, but it just seems far too ugly.
> (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.
That might be a good possibility. Thanks for the idea! I do consider it
quite a bit ugly, but that often happens when languages try to police
programmers... :P
> 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?
Well basically, I'm rewriting a autodownloader for a file-sharing
network in Python (previously written as a bash script, using the printf
command), and I have a number of files scattered over my hard drive
specifying search expressions, into which a potentially optional episode
number can be inserted using sprintf-like arguments (using
fsexpr="`printf "$sexpr" "$curep"`" in bash). I would like to keep it as
a printf parameter, in order to be able to write e.g. %02i, and I would
like to keep it optional, for downloading non-episoded stuff.
I couldn't help noticing that the named variant of the % operator (using
a dict, that is) doesn't require all its arguments to be consumed. Using
that would require me to rewrite *all* the existing files, though.
Anyway, thanks!
Fredrik Tolf
More information about the Python-list
mailing list