close

[Solved] Python: TypeError: cannot concatenate ‘str’ and ‘int’ objects

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Python: TypeError: cannot concatenate ‘str’ and ‘int’ objects in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Python: TypeError: cannot concatenate ‘str’ and ‘int’ objects Error Occurs?

Today I get the following error Python: TypeError: cannot concatenate ‘str’ and ‘int’ objects in python.

How To Solve Python: TypeError: cannot concatenate ‘str’ and ‘int’ objects Error ?

  1. How To Solve Python: TypeError: cannot concatenate 'str' and 'int' objects Error ?

    To Solve Python: TypeError: cannot concatenate 'str' and 'int' objects Error str(c) returns a new string representation of c, and does not mutate c itself.

  2. Python: TypeError: cannot concatenate 'str' and 'int' objects

    To Solve Python: TypeError: cannot concatenate 'str' and 'int' objects Error str(c) returns a new string representation of c, and does not mutate c itself.

Solution 1


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: 3
Enter b: 7
a + b as strings:  37
a + 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 strings
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: ", c

Solution 2

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

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read