string formatting with mapping & '*'... is this a bug?
Pierre Fortin
pfortin at pfortin.com
Thu Sep 9 15:23:28 EDT 2004
On 9 Sep 2004 18:45:37 GMT OKB wrote:
> Pierre Fortin wrote:
>
> > Attempting to specify a field width via '*' to a mapping fails....
> >
> >>>> "%(two)*d" % (mapping,6)
> > Traceback (most recent call last):
> > File "<stdin>", line 1, in ?
> > TypeError: format requires a mapping
> >>>> "%(two)-*d" % (6,mapping)
> > Traceback (most recent call last):
> > File "<stdin>", line 1, in ?
> > TypeError: format requires a mapping
>
> I don't think this has anything to do with the * thing. You can't
>
> mix the sequence and mapping forms of %. For instance, this also fails
>
> >>> m = {'one': 1, 'two': 2}
> >>> "%(two)d %d" % (m, 6)
>
> Traceback (most recent call last):
> File "<pyshell#8>", line 1, in -toplevel-
> "%(two)d %d" % (m, 6)
> TypeError: format requires a mapping
>
> The error message is telling you the truth: you're passing the %
> operator a tuple, but your format string has a "%(two)" in it, which
> means it requires not a tuple but a mapping.
>
Darn... I was hoping that Python would let me format strings with
mappings in a more readable/maintainable way than thusly:
>>> mapping = {'one':1,'two':2,'size':6}
>>> eval("'%%(two)%(size)dd' %% mapping" % mapping)
' 2'
-or-
>>> size=6
>>> eval("'%%(two)%dd' %% mapping" % size)
' 2'
Changing my copy of the book on P.48 to read:
"""
In addition, the asterisk (*) character may be used in place of any number
in any** width field. If present, the width will be read from the next
item in the tuple.
** EXCEPT with mappings described in (1) above
"""
Pierre
More information about the Python-list
mailing list