TypeError: cannot concatenate 'str' and 'int' objects
Solution 1
%
has a higher precedence than +
, so s % y + z
is parsed as (s % y) + z
.
If s
is a string, then s % x
is a string, and (s % y) + z
attempts to add a string (the result of s % y
) and an integer (the value of z
).
Solution 2
You need to put parenthesis: (y+z)
daGrevis
Hacker working with Clojure, Python, ReactJS and Docker. Enjoys r/unixporn and r/vim. Loves DotA 2, blues rock and gym. Really loves his girlfriend. https://twitter.com/daGrevis https://github.com/daGrevis https://news.ycombinator.com/user?id=daGrevis https://lobste.rs/u/daGrevis http://www.linkedin.com/in/daGrevis
Updated on June 14, 2022Comments
-
daGrevis almost 2 years
I'm learning Python now, yay! Anyway, I have small problem. I don't see problem in here:
x = 3 y = 7 z = 2 print "I told to the Python, that the first variable is %d!" % x print "Anyway, 2nd and 3rd variables sum is %d. :)" % y + z
But Python thinks different -
TypeError: cannot concatenate 'str' and 'int' objects
.Why is that so? I haven't setted any variable as string... as much as I see.
-
carlosdc over 12 yearsIf not python thinks you're doing ("Anyway %d" % y)+z
-
Dan D. over 12 years
%
has lower precedence than+
, soa % b + c
is parsed as(a % b) + c
, while what you want isa % (b + c)
-
nagisa over 12 yearsBecause it formats string with
y
ant then tries to concatenate formatted string withz
, which yields error, because they are of different types. -
MaddTheSane over 12 yearsGrammar reference: docs.python.org/reference/…
-
daGrevis over 12 yearsThanks for answers, guys! I just smell that learning Python will be so much fun for me! :))