Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: cannot concatenate 'str' and 'int' objects

I don't see problem in here, but Python thinks different:

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

I get TypeError: cannot concatenate 'str' and 'int' objects.

Why is that so? I haven't setted any variable as string... as much as I see.

like image 766
daGrevis Avatar asked Nov 30 '22 16:11

daGrevis


1 Answers

% 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).

like image 64
MRAB Avatar answered Dec 04 '22 10:12

MRAB