TypeError: can only concatenate str (not "int") to str

TypeError: can only concatenate str (not "int") to str

The error "TypeError: can only concatenate str (not 'int') to str" occurs when you are trying to concatenate a string with an integer. To fix this error, you will need to convert the integer to a string before you can concatenate it with the string. You can do this by using the str() function.

Solution

For example, suppose you have the following code:

num = 10
string = "The value of num is: " + num

This will give you the error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

To fix the error, you can use the str() function to convert the integer to a string, like this:

num = 10
string = "The value of num is: " + str(num)

This will produce the string "The value of num is: 10", which you can then use or print as needed.

Alternatively, you can also use string formatting to insert the value of the integer into the string. For example:

num = 10
string = "The value of num is: {}".format(num)

This will also produce the string "The value of num is: 10".

Related: