Bug in % string formatting?
Jeff Shannon
jeff at ccvcorp.com
Thu Dec 20 16:27:10 EST 2001
Fernando Pérez wrote:
> If this is not a bug in % string formatting, I'd love to understand what is
> going on.....
It's not a bug, it's just mistaken assumptions. ;)
> # This works ok
> print 'With prebuilt list:'
> print format_string % format_list
>
> # but this fails. The format string is copied verbatim from above
> print 'Explicit list construction:'
> print format_string % names['John'][:] + names['Jane'][:]
>>> # Your first example
>>> format_list = names['john'][:] + names['jane'][:]
>>> format_string % format_list
'johnnie <john at nowhere.com>\njane doe <jane at nowhere.com>'
>>> # This breaks...
>>> format_string % names['john'][:] + names['jane'][:]
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: not enough arguments for format string
>>> # But with parentheses....
>>> format_string % (names['john'][:] + names['jane'][:])
'johnnie <john at nowhere.com>\njane doe <jane at nowhere.com>'
>>>
The problem is that the % operator is processing before the + operator, so
you're trying to format your string with only john's info, and then adding the
tuple of jane's info to that string....
By putting parenthesis around the tuple-addition, I'm forcing that to happen
first. Then the resulting tuple has enough values to satisfy the format
string.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list