[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.

Related Posts

  • Python check for null
    17 November

    How to check for null in Python

    Table of ContentsHow to check if a variable is NULL in Python?Using the is operator to check if a variable is NULL in Python.Using the if condition to check if a variable is NULL in Python.Using the not equal to operator to check if a variable is NULL in Python. This article demonstrates the different […]

  • Sort dictionary by value in Python
    17 November

    Sort dictionary by value in python

    Table of ContentsHow to sort sort dictionary by value in Python?Using for loop along with the sorted() function.Using the sorted() function to sort dictionary by value in Python.Using operator.itemgetter() function to sort sort dictionary by value in Python.Using lambda function to sort sort dictionary by value in Python.Using the OrderedDict() method to sort sort dictionary […]

  • Get class name in Python
    17 November

    Get class name in Python

    Table of ContentsHow to get the attributes of an object?Get Class name in python using the __class__ attribute Get Class name in python using type() functionConclusion While working with objects in python, several times we need to get their class name. In this article, we will discuss several ways to get the class name of an […]

  • Python print to file
    17 November

    How to Print to File in Python?

    Table of ContentsThe print() function in pythonHow to Print to file in python?Print to file using the file parameter in the print functionPrint to file by redirecting standard outputConclusion We use the print() function in python to print any text to standard output. In this article, we will see how we can use the print() […]

  • Python absolute path
    17 November

    Get Absolute Path in Python

    Table of ContentsWhat is an absolute path to a file? How to get absolute path in PythonUse abspath to get the absolute path to file use pathlib module to get the absolute path to file Conclusion We often use files to store the outputs of our programs in permanent storage. Generally, we work with relative […]

  • Python sort list of lists
    17 November

    Sort List of Lists in Python

    Table of ContentsSort List of Lists Using the sort() Method in PythonUsing the itemgetter() methodUsing Lambda FunctionsSort List of Lists Using the sorted() Function in PythonSort lists of lists on the basis of the length of the inner listsConclusion Several times we use 2-D lists or lists of lists in our programs to represent a […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.