String formatters with variable argument length
Peter Otten
__peter__ at web.de
Fri Dec 1 04:24:33 EST 2006
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.
> what's ugly about this:
> [untested]:
>
> def count_format_args(s):
> pending = False
> count = 0
> for c in s:
> if c == "%":
> # doubled % chars aren't counted
> pending = not pending
> elif pending:
> count += 1
> pending = False
> return count
>
> output = format % arglist[:count_format_args(format)]
Keep in mind, though, that it doesn't take '*' into account:
>>> count_format_args("%*.*f")
1
>>> "%*.*f" % (3,2,1)
'1.00'
And just because I don't think I've seen it before:
>>> count_format_args("%42%")
1
>>> "%42%" % ()
' %'
Peter
More information about the Python-list
mailing list