Correct behavior?

A

asker

Hello:
I have next Python 2.5.1 instructions:
23.57

But: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?

Thanks
 
D

DanBishop04

Hello:
I have next Python 2.5.1 instructions:


23.57

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.
 
M

Mitja Trampus

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top