Bug in % string formatting?

Bjorn Pettersen BPettersen at NAREX.com
Thu Dec 20 16:00:53 EST 2001


> From: Fernando Pérez [mailto:fperez528 at yahoo.com] 
> 
> If this is not a bug in % string formatting, I'd love to 
> understand what is 
> going on.
> 
> The example code is:
> 
> names = {'John' : ('John Doe','jodoe at nowhere'),
>          'Jane' : ('Jane Doe','jadoe at nowhere'),
>          }
> 
> format_string = '%s <%s>\n%s <%s>'
> 
> format_list = names['John'][:] + names['Jane'][:]
> 
> # 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'][:]

The % operator binds tighter than +, so what you really wrote above
(minus useless [:]) was:

  print (format_string % names['John']) + names['Jane']

To get what you expected you need to use explicit parentheses:

  print format_string % (names['John'] + names['Jane'])

Hth,
-- bjorn




More information about the Python-list mailing list