[Solved] TypeError: Can only Concatenate str (not “int”) to str

Summary: To eliminate the TypeError - can only concatenate str (not "int") to str typecast all the values into a single type.

Problem Formulation: How to fix Typeerror: can only concatenate str (not "int") to str in Python?

Example:

Output:

Traceback (most recent call last):
File “main.py”, line 1, in
print(’10’+5) # expected output: 15
TypeError: can only concatenate str (not “int”) to str

What is “TypeError” in Python?

In Python, a TypeError occurs when you perform an incorrect function call or use an incorrect operator type. For instance, let’s see what happens when we include two inconsistent types:

Example:

Output:

Traceback (most recent call last):
File “D:/PycharmProjects/PythonErrors/rough.py”, line 2, in
print(var[1])
TypeError: ‘int’ object is not subscriptable

Python throws a TypeError because int type objects are not accessible by using the index. To access an element using its index- you must create a list, tuple, or string type objects.

What does TypeError: can only concatenate str (not “int”) to str mean ?

To understand this Typeerror, let’s consider the following example:

Output:

8
johnmonty
green green green
Traceback (most recent call last):
File “main.py”, line 4, in
print(‘Java’ + 2 + ‘Blog’) # Concatenating two strings and an integer
TypeError: can only concatenate str (not “int”) to str

The first three lines of code work fine because the concatenation between the same types and multiplication between an integer and a string is allowed in Python.

✨ As Python is a dynamic programming language, the first three lines of code are executed, and then Python throws TypeError: can only concatenate str (not "int") to str because concatenating a string and a numeric value (int) is not allowed in Python.

Now that we know the reason behind the occurrence of this error, let’s dive into the solutions:

Solution 1: Use Same Data Types

Instead of concatenating an integer and a string, you can locate the line within your code causing the error. Then rectify it to ensure that you concatenate two values of the same type, i.e., both the values are strings.

You can easily identify and eliminate the TypeError by utilizing an IDE that checks for errors. If you don’t have any idea where the bug is and you are not utilizing the IDE, it is beneficial to download one as it makes it simpler to discover the bug in the code.

The Solution:

Output:

15
Java2Blog

In any case, this method is incapable of more complex codes since you do it all manually! 😉

Solution 2: Typecasting The Data Types to Concatenate/Add Similar Types

Discover in which line of code TypeError showed up and then typecast the values to represent the same type. 

  • When you want to add two numbers, you have to typecast both values to ‘int‘.
  • When you want to concatenate two texts, typecast them to ‘str‘.

Output:

15
Java2Blog

⚠️ Caution:  This method isn’t ideal when you have a ton of data that you need to combine because it is a cumbersome task to manually typecast every variable one by one.

Solution 3: Using The format() Function

❖ The format() function is used in Python for String Concatenation. This function joins various elements inside a string through positional formatting.

Example:

Output:

John13

The braces (“{}”) are utilized here to fix the string position. The variable ‘a’ is stored in the first brace, and the second variable ‘b’ gets stored in the second curly brace. The format() function combines the strings stored in both variables “a” and “b” and displays the concatenated string.

Solution 4: Using The join() and str() Function Together

The join() method is the most adaptable method of concatenating strings in Python. If you have numerous strings and you need to combine them, use the join() function. The most interesting thing about join() is that you can concatenate strings utilizing a separator. Hence, it also works at iterators like tuples, strings, lists, and dictionaries. 

To combine integers into a single string, apply the str() function to every element in the list and then combine them with the join() as shown below.

Output:

0-1-2

Solution 5: Use Function

Another approach to resolve our problem is to create a convert function that converts a variable from one type to another.

Example:

Output:

First: Converting To String
<class ‘str>’
<class ‘str’>
Output: Python 3.18
Second: Converting To Integer
<class ‘int’>
<class ‘int’>
Output: 15

If there are more than two variables that you need to convert using a list as shown below.

Output:

String values:
[, , ]
[’20’, ’25’, ’43’]
Integer values:
[, , ]
[20, 25, 43]
45

Conclusion

I hope you found this article helpful. Please stay tuned and subscribe for more interesting articles! 📚

This article was submitted by Rashi Agarwal and edited by Shubham Sayon.

Was this post helpful?

Leave a Reply

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