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

14,475

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)

Share:
14,475
daGrevis
Author by

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, 2022

Comments

  • daGrevis
    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
    carlosdc over 12 years
    If not python thinks you're doing ("Anyway %d" % y)+z
  • Dan D.
    Dan D. over 12 years
    % has lower precedence than +, so a % b + c is parsed as (a % b) + c, while what you want is a % (b + c)
  • nagisa
    nagisa over 12 years
    Because it formats string with y ant then tries to concatenate formatted string with z, which yields error, because they are of different types.
  • MaddTheSane
    MaddTheSane over 12 years
    Grammar reference: docs.python.org/reference/…
  • daGrevis
    daGrevis over 12 years
    Thanks for answers, guys! I just smell that learning Python will be so much fun for me! :))