Correct behavior?
Mitja Trampus
nun at example.com
Fri Apr 27 13:23:47 EDT 2007
DanBishop04 at gmail.com wrote:
> On Apr 26, 8:34 pm, asker <vizcay... at gmail.com> wrote:
>> But:>>> print "%15.2f" % a+b
>>
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>> TypeError: cannot concatenate 'str' and 'float' objects
>>
>> Is this correct for Python to issue this error?
>
> The % operator has higher precedence than +. Thus, "%15.2f" % a+b ==
> ("%15.2f" % a)+b, an illegal str+float addition.
Just as a warning:
If you're not expecting this behavior, you can get a pretty
nasty surprise if the adddition in question is str+str and
the operation becomes legal (but semantically different):
s1 = "Captain "
s2 = "Bertorelli"
print "Ah, %s! Welcome to my humble cafe..." % s1+s2
--> "Ah, Captain ! Welcome to my humble cafe...Bertorelli"
Of course this can (and should) be avoided using
"...%s%s..." % (s1,s2), but I know it has bitten me once.
More information about the Python-list
mailing list