Enumerating formatting strings
Peter Otten
__peter__ at web.de
Wed Apr 20 05:01:28 EDT 2005
Bengt Richter wrote:
> 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 ;-)
Which it doesn't:
>>> def tupreq(fmt): return sum(map(lambda s:list(s).count('%'),
fmt.split('%%')))
...
>>> fmt = "%*d"
>>> fmt % ((1,) * tupreq(fmt))
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: not enough arguments for format string
> 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
Mixed formats show some "interesting" behaviour:
>>> "%s %(x)s" % (1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: format requires a mapping
>>> class D:
... def __getitem__(self, key):
... return "D[%s]" % key
...
>>> "%s %(x)s" % D()
'<__main__.D instance at 0x402aaf2c> D[x]'
>>> "%s %(x)s %s" % D()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: not enough arguments for format string
>>> "%s %(x)s %(y)s" % D()
'<__main__.D instance at 0x402aad8c> D[x] D[y]'
That is as far as I got. So under what circumstances is
'%s this %(x)s not %% but %s' a valid format string?
Peter
More information about the Python-list
mailing list