Python - How To Fix Python Cannot Concatenate STR and Int Objects Error

ID : 26

viewed : 227

Tags : PythonPython StringPython Error

vote vote


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.

We will tell you how you can resolve this error in Python.

Fix cannot concatenate 'str' and 'int' objects Error in Python

Take a look at the following code.

#String variable s1="Hello"  #integer variable number=5 #Trying to concatenate string with integer s2=s1+number 

If we concatenate a string and an integer in the above code example, it will give this exact error cannot concatenate 'str' and 'int' objects. So, how can we avoid this error? Take a look.

#String variable s1="Hello"  #integer variable number=5  #Converting integer to string  number_str=str(number)  #Concatenate number to a string s2=s1+number_str print(s2) 

We can convert the integer into a string first and later concatenate those two strings.

The idea here is that you can only concatenate two strings, not a string or any other data type. Therefore, if you need to concatenate a string with a different structure, you must first convert it into a string.

  • Related HOW TO?