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?
You are watching: Typeerror: can only concatenate str (not "int") to str
Traceback (most recent call last):File “main.py”, line 1, inprint(’10’+5) # expected output: 15TypeError: 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:
Traceback (most recent call last):File “D:/PycharmProjects/PythonErrors/rough.py”, line 2, inprint(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:
print(3 + 5)# adding two integers
print(“john” + “monty”)# concatenating two strings
print(“green ” * 3)# multiplying an int and a string
print(“Java” + 2 + “Blog”)# Concatenating two strings and an integer
8johnmontygreen green greenTraceback (most recent call last):File “main.py”, line 4, inprint(‘Java’ + 2 + ‘Blog’) # Concatenating two strings and an integerTypeError: 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.