Enumerating formatting strings
Bengt Richter
bokr at oz.net
Wed Apr 20 04:22:54 EDT 2005
On Wed, 20 Apr 2005 09:14:40 +0200, Peter Otten <__peter__ at web.de> wrote:
>Greg Ewing wrote:
>
>> Steve Holden wrote:
>>
>>> I've been wondering whether it's possible to perform a similar analysis
>>> on non-mapping-type format strings, so as to know how long a tuple to
>>> provide,
>>
>> I just tried an experiment, and it doesn't seem to be possible.
>>
>> The problem seems to be that it expects the arguments to be
>> in the form of a tuple, and if you give it something else,
>> it wraps it up in a 1-element tuple and uses that instead.
>>
>> This seems to happen even with a custom subclass of tuple,
>> so it must be doing an exact type check.
>
>No, it doesn't do an exact type check, but always calls the tuple method:
>
>>>> class Tuple(tuple):
>... def __getitem__(self, index):
>... return 42
>...
>>>> "%r %r" % Tuple("ab") # would raise an exception if wrapped
>"'a' 'b'"
>
>> So it looks like you'll have to parse the format string.
>
>Indeed.
>
Parse might be a big word for
>> def tupreq(fmt): return sum(map(lambda s:list(s).count('%'), fmt.split('%%')))
..
>> tupreq('%s this %(x)s not %% but %s')
(if it works in general ;-)
Or maybe clearer and faster:
>>> def tupreq(fmt): return sum(1 for c in fmt.replace('%%','') if c=='%')
...
>>> tupreq('%s this %(x)s not %% but %s')
3
Regards,
Bengt Richter
More information about the Python-list
mailing list