Format Strings -- Real vs. Expected Behaviour

Grant Edwards grante at visi.com
Mon Apr 16 21:04:04 EDT 2001


In article <NpMC6.4660$4I5.385432 at news1.rdc1.mb.home.com>, Brad Bollenbach wrote:

>    print "%s " + \
>    "%s" % ("hello", "world")
>
>Results in "TypeError: not all arguments converted".

>but this:
>
>    print ("%s " + \
>    "%s") % ("hello", "world")
>
>prints "hello world" as well.
>
>Shouldn't Python be smart enough to know that even without ()'s around the
>whole thing, this is all one line (therefore avoiding the current
>odd/unexpected IMHO behaviour with the format string)? After all, I'm
>telling it this much by using the line continuation character "\" aren't I?

It's got nothing to do with the continuation character or being all one
line. Putting it all on one line results in the same "unexpected" behavior:

>>> print "%s " + "%s" % ('hello', 'world')
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: not all arguments converted

The "%" operator has a higher precedence than the "+" operator.
Without the explicit grouping, what you have is (in effect)

print "%s" + ("%s" % ('hello','world))

The format "%" operator sees the format sting "%s" and the data value of
('hello','world').  You've provided two pieces of data and a format string
that only converts one of them.

-- 
Grant Edwards                   grante             Yow!  Two LITTLE black
                                  at               dots and one BIG black
                               visi.com            dot...nice 'n' FLUFFY!!



More information about the Python-list mailing list