Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Why can't Python concatenate str and int objects?

In Python, we cannot concatenate a string and an integer together. They have a different base and memory space as they are completely different data structures.

Why cannot concatenate Python?

Python does not support the auto type of the variable to be cast. You can not concatenate an integer value to a string. The root cause of this issue is due to the concatenation between an integer value and a string object. Before concatenation, an integer value should be converted to a string object.

Can only concatenate str not NoneType to str Python?

The Python "TypeError: can only concatenate str (not "NoneType") to str" occurs when we try to concatenate a string and a None value. To solve the error, correct the assignment or check if the variable doesn't store a None value before concatenating.


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

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 = 123
a = "foobar"
s = a + str(i)

c = a + b 
str(c)

Actually, in this last line you are not changing the type of the variable c. If you do

c_str=str(c)
print "a + b as integers: " + c_str

it should work.


Apart from other answers, one could also use format()

print("a + b as integers: {}".format(c))

For example -

hours = 13
minutes = 32
print("Time elapsed - {} hours and {} minutes".format(hours, minutes))

will result in output - Time elapsed - 13 hours and 32 minutes

Check out docs for more information.


You can convert int into str using string function:

user = "mohan"

line = str(50)

print(user + "typed" + line + "lines")