TypeError: can only concatenate str (not “int”) to str

The TypeError: can only concatenate str (not “int”) to str error occurs when we try to add the integer value with the strings. There can be many possible scenarios where you get this error but the most common reason is when you append an integer value to the string value using plus operator. Also, sometimes, you get the same error when you try to add an integer to a list or any other data type. In this short article, we will discuss how we can solve TypeError: can only concatenate str (not “int”) to str error using various methods. Moreover, we will also discuss how to understand errors in Python by taking this error as an example.

TypeError: can only concatenate str (not “int”) to str – Possible solutions

We know that the TypeError: can only concatenate str (not “int”) to str error occurs when we try to add an integer value to the string using the plus operator. We get the same error when we try to add integer values to lists or any other data types as well. The error seems to be complicated but it is very simple to solve and get rid of it.

In Python, every data types have its own method and operation and we cannot apply every operation to all type of data types. For example, one of the operations that are not allowed in Python is to add or append an integer value to the string value directly. However, there are some techniques and methods through which such operations are possible.

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

Now, let us discuss the possible reasons for getting this error and solutions as well. We will solve the error using the following methods:

  • Convert integer to string
  • Printing integer results
  • Correctly printing dictionary

Solution-1: Convert integer to string

The most common reason for getting TypeError: can only concatenate str (not “int”) to str error is the difference in the data type of the variables. For example, let us say that we have two different variables and we want to add them as shown below:

# variables
name = "Bashir"
age = 22

# adding infor
ifo = 'My name is '+ name + ". My age is " + age

# print
print(ifo)

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_204684/2698557346.py in <module>
      4 
      5 # adding infor
----> 6 ifo = 'My name is '+ name + ". My age is " + age
      7 
      8 # print

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

The reason for getting this error is because of the difference in the data type. The age variable in our case is an integer and it cannot be directly added to string values.

The simplest solution is to convert the integer value into a string value and add it to the string as shown below:

# variables
name = "Bashir"
age = 22

# adding infor
ifo = 'My name is '+ name + ". My age is " + str(age)

# print
print(ifo)

Output:

My name is Bashir. My age is 22

Notice that we used the str() method to convert the integer object into a string object.

Solution-2: Printing integer result

Sometimes, we may get the error while printing an integer value with a string. For example, let us take the same example and solved it using various possible methods.

# variables
name = "Bashir"
age = 22

# printing the result
print("My age is : " + age)

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_204684/35949242.py in <module>
      4 
      5 # printing the result
----> 6 print("My age is : " + age)

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

Notice that we got the error again because of the difference in the data types.

One way to solve the error is to convert the integer value into a string value as shown in the first part. The second method is to use comma operator soon after the string and add an integer value as shown below:

# variables
name = "Bashir"
age = 22

# printing the result
print("My age is : ",  age)

Output:

My age is :  22

Notice that we solve the error by replacing the plus operator with the comma operator.

Another alternative method is to use the f’ ‘ string. See the example below of how we can use the f’ ‘ string to solve the given error:

# variables
name = "Bashir"
age = 22

# printing
print(f'My age is : {age}')

Output:

My age is :  22

As you can see, we were able to print the result without getting TypeError: can only concatenate str (not “int”) to str error.

There is another way to solve the error using the .format method. In Python, we can add different data types to the print statement using the .format method as shown below:

# variables
name = "Bashir"
age = 22

# printing
print('My age is :{}'.format(age))

Output:

My age is :22

Notice that we added the age to the string variable using the .format method without getting any error.

Solution-3: Correctly print dictionary values

Sometimes, we get the same error while accessing and printing the elements from the dictionary. Let us first take an example and see why we are getting this error.

salary_dict = {
    'CS' : 80, 
    'CM' : 120, 
}

for employee, salary in salary_dict.items():
    print('Position:'+employee, 'Salary:' + salary)

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_204684/3119686148.py in <module>
      5 
      6 for employee, salary in salary_dict.items():
----> 7     print('Position:'+employee, 'Salary:' + salary)

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

As you can see, we got the error because we are trying to add the integer value with the string.

The solution to the above problem is to use {} brackets. See the example below, how we have used the curly brackets to get rid of the error.

salary_dict = {
    'CS' : 80, 
    'CM' : 120, 
}

for employee, salary in salary_dict.items():
    print(f'Position:{employee}, Salary: {salary}')

Output:

Position:CS, Salary: 80
Position:CM, Salary: 120

Notice that we solved the error without getting any errors.

Understanding TypeError: can only concatenate str (not “int”) to str in Python

In Python, errors give us a lot of information that we can use in order to figure them out and solve them. Usually, an error in Python has two main parts. The first part of the error gives information about the category of the error. For instance, the category of the given problem is TypeError because it belongs to a type error.

While the second part of the error gives more specific information and helps us to figure out what kind of type error is there in our code. It clearly says that we are not allowed to concatenate integer values to the string values which means in our code we are adding an integer value to the string.

Possible reasons for getting an error

This error occurs when you try to concatenate (join) a string with an integer using the “+” operator. This is not allowed because Python does not know how to combine different data types. Here are some possible reasons why you might encounter this error:

  1. Using the “+” operator to concatenate a string and an integer: If you try to concatenate a string and an integer using the “+” operator, Python will raise a TypeError. For example, “Hello” + 42 will raise this error because you are trying to concatenate a string with an integer.
  2. Trying to add an integer to a string using the “+” operator: This error can also occur if you try to add an integer to a string using the “+” operator. For example, 42 + “Hello” will raise this error because you are trying to add an integer to a string.
  3. Using an integer variable where a string is expected: If you try to use an integer variable where a string is expected, you may encounter this error. For example, if you try to print an integer variable inside a string using f-strings like f”Hello {42}”, you will get a TypeError.
  4. Incorrect formatting of string: If you are trying to format a string and you have made a mistake in the syntax, you may get this error. For example, if you forget to use the “%” operator to format a string, you may see this error.
  5. Using the wrong variable or data type: If you have inadvertently used the wrong variable or data type in your code, you may get this error. For example, if you meant to use a string variable but used an integer variable instead, you may see this error.

Summary

In this short article, we discussed how we can solve TypeError: can only concatenate str (not “int”) to str error in Python using various methods. We mainly covered three different methods and scenarios where we get TypeError: can only concatenate str (not “int”) to str error and solve the issue.

Related Issues

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top