开发者

"TypeError: cannot concatenate 'str' and 'int' objects" when trying to use printf-style formatting

开发者 https://www.devze.com 2023-03-26 21:34 出处:网络
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

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 an开发者_Go百科y variable as string... as much as I see.


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


You need to put parenthesis: (y+z)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号