Python: TypeError: cannot concatenate 'str' and 'int' objects [duplicate] Python: TypeError: cannot concatenate 'str' and 'int' objects [duplicate] python python

Python: TypeError: cannot concatenate 'str' and 'int' objects [duplicate]


There are two ways to fix the problem which is caused by the last print statement.

You can assign the result of the str(c) call to c as correctly shown by @jamylak and then concatenate all of the strings, or you can replace the last print simply with this:

print "a + b as integers: ", c  # note the comma here

in which case

str(c)

isn't necessary and can be deleted.

Output of sample run:

Enter a: 3Enter b: 7a + b as strings:  37a + b as integers:  10

with:

a = raw_input("Enter a: ")b = raw_input("Enter b: ")print "a + b as strings: " + a + b  # + everywhere is ok since all are stringsa = int(a)b = int(b)c = a + bprint "a + b as integers: ", c


str(c) returns a new string representation of c, and does not mutate c itself.

c = str(c) 

is probably what you are looking for


If you want to concatenate int or floats to a string you must use this:

i = 123a = "foobar"s = a + str(i)