Format Strings -- Real vs. Expected Behaviour

Jose' Sebrosa sebrosa at artenumerica.com
Mon Apr 16 21:13:56 EDT 2001


Brad Bollenbach wrote:
> 
> Just curious, from Python 2.0...
> 
> This:
> 
>     print "%s %s" % ("hello", "world")
> 
> prints "hello world"
> 
> whereas this:
> 
>     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?

Python knows that it is all one line.  The line is
print "%s " + "%s" % ("hello", "world")

In this line you have two string operators: "+" and "%". The operator "%" takes
precedence over "+", so the implied parenthesis are like this:

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

Sebrosa



More information about the Python-list mailing list