Fix Python Cannot Concatenate STR and Int Objects Error

Fix Python Cannot Concatenate STR and Int Objects Error

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.

Author: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

Related Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • Extract Numbers From a String in Python
  • Convert String to Datetime in Python
  • Related Article - Python Error

  • Python PermissionError: [WinError 5] Access Is Denied
  • Python TypeError: 'DataFrame' Object Is Not Callable
  • Python TypeError: Can't Convert 'List' Object to STR
  • Local Variable Referenced Before Assignment Error in Python
  • Python Handling Socket.Error: [Errno 104] Connection Reset by Peer
  • Python Is Not Recognized in Windows 10