Что означает ошибка TypeError: can only concatenate str (not «int») to str
Это значит, что вы пытаетесь сложить строки с числами
Это значит, что вы пытаетесь сложить строки с числами
Программист освоил JavaScript и начал изучать Python. Чтобы освоиться в языке, он переносит проекты с одного языка на другой — убирает точки с запятой, добавляет отступы и меняет команды одного языка на такие же команды из другого языка.
Один из фрагментов его кода после перевода в Python выглядит так:
# зарплата в месяц
month = 14200
# плата за ЖКХ
regular_cost = 5800
# функция, которая считает и возвращает долю ЖКХ в бюджете
def calculate(budget,base):
message = 'На коммунальные платежи уходит ' + base + 'р. - это ' + base/budget*100 + ' процентов от ежемесячного бюджета'
return message
# отправляем в функцию переменные и выводим результат на экран
print(calculate(month,regular_cost))
Но после запуска программист получает ошибку:
❌ TypeError: can only concatenate str (not «int») to str
Странно, но в JavaScript всё работало, почему же здесь код сломался?
Что это значит: компилятор не смог соединить строки и числа, поэтому выдал ошибку.
Когда встречается: в языках со строгой типизацией, например в Python, когда у всех переменных в выражении должен быть один и тот же тип данных. А вот в JavaScript, который изучал программист до этого, типизация нестрогая, и компилятор сам мог привести все части выражения к одному типу.
Что делать с ошибкой TypeError: can only concatenate str (not «int») to str
Раз это проблема строгой типизации, то для исправления этой ошибки нужно просто привести все части к одному типу.
В нашем случае мы хотим получить на выходе строку, поэтому все слагаемые должны быть строкового типа. Но base и base/budget*100 — это числа, поэтому просто так их сложить со строками не получится. Чтобы выйти из ситуации, явно преобразуем их в строки командой str():
message = 'На коммунальные платежи уходит ' + str(base) + 'р. - это ' + str(base/budget*100) + ' процентов от ежемесячного бюджета'
Команда str() делает так, что всё внутри неё приводится к строке и она отдаёт дальше строку. В итоге операция склейки строк проходит как ожидаемо: строка к строке даёт строку. Нет повода для беспокойства.
Вёрстка:
Кирилл Климентьев
TypeError: can only concatenate str (not “int”) to str as the name is evident occurs when a value other than str type is tried to concatenated together. Often, beginners face this issue; however, don’t fret; it is easy to resolve.
In the following article, we will discuss type errors, how they occur and how to resolve TypeError: can only concatenate str (not “int”) to str. You can also check out our other articles on TypeError here.
What is a TypeError?
The TypeError occurs when you try to operate on a value that does not support that operation. For instance, let’s take a simple example of adding two variables.
var1 = 10 var2 = "string" print(var1 + var2)
What do you expect the output to be? It is clear that a string and an integer can’t be added together. The only solution is to have operands with similar data types.
Similarly, as shown in the example above, we can only concatenate strings together. Let’s see an example of the TypeError we are facing.
string = "Some random text" int_value = 99 print(string + int_value)
Here we have taken string and int_value, which are string and integer data types. On trying to concatenate these two, TypeError gets thrown.
l = ['random text', 'more random text', 10] print(l[0] + l[2])
The following program grabs the 0th index item and the 2nd index item of the list and concatenates them. However, since both items are of different data types, we get a type error. It is essential to realize that only strings can be concatenated together. Hence, the error TypeError: can only concatenate str (not “int”) to str.
Languages like JavaScript support type coercion which automatically converts values like integers and float so that they can be concatenated. However, this is done under some rules.
How to resolve the error, can only concatenate str (not “int”) to str?
The only way to resolve this error is to convert the integer or the float value to a string before concatenating them. This will prevent errors from being thrown on screen while the program executes.
Let’s look at an example of how this can be done:
Example
book_store = [
{
'name' : 'Kafka on the shore',
'author' : 'Haruki Murakami',
'release_yr' : 2002
},
{
'name' : 'Crime and Punishement',
'author' : 'Fyodor Dostoevsky',
'release_yr' : 1886
}
]
print(book_store[0]['name'] + ' ' + book_store[0]['release_yr'])
print(book_store[1]['name'] + ' ' + book_store[1]['release_yr'])
Solution 1:
To resolve the type error, we need to make sure the release_yr value is a string, not an integer.
print(book_store[0]['name'] + ' ' + str(book_store[0]['release_yr'])) print(book_store[1]['name'] + ' ' + str(book_store[1]['release_yr']))
Solution 2:
Using f-strings, str.format, or even %s of string formatting can resolve this error. All these methods, before string formatting, convert values to an str type, thus eliminating the possibility of type error being raised.
# using f-strings
print(f"{book_store[0]['name']} {book_store[0]['release_yr']}")
print(f"{book_store[1]['name']} {book_store[1]['release_yr']}")
#using format method
print('n{} {}'.format(book_store[0]['name'],book_store[0]['release_yr']))
print('{} {}'.format(book_store[1]['name'],book_store[1]['release_yr']))
# using string formatting
print('n%s %s' %(book_store[0]['name'],book_store[0]['release_yr']))
print('%s %s' %(book_store[1]['name'],book_store[1]['release_yr']))
Can only concatenate str (not “int”) to str in a dataframe pandas
import pandas as pd
books = {
"BookName": [
"The Godfather",
"Catch-22",
"The Lighthouse",
"The Fault in Our Stars",
],
"Author": [
"Mario Puzo",
"Joseph Heller",
"Virginia Woolf",
"John Green",
],
"ReleaseYear": [1969, 1961, 1927, 2012],
}
books_df = pd.DataFrame(books, columns=["BookName", "Author", "ReleaseYear"])
books_df["BookRelease"] = books_df["BookName"] + "-" + books_df["ReleaseYear"]
print(books_df)
- We have created a dataframe named books_df, which contains columns, namely – BookName, Author, and ReleaseYear.
- Then, we are trying to concatenate the column’s BookName and the ReleaseYear. The resultant column being named BookRelease.
- However, an error gets thrown since we are trying to concatenate string and integer.
To resolve this error, use the astype method of pandas and convert the ReleaseYear column values to string data type.
books_df["BookRelease"] = (
books_df["BookName"] + "-" + books_df["ReleaseYear"].astype(str)
)
print(books_df)
FAQs
How to avoid type error can only concatenate str (not “int”) to str?
To prevent this error, make sure items being concatenated are of the same type, i.e., string.
How to catch type error can only concatenate str (not “int”) to str?
Try-except block can be used to catch the type error. For instance:try:
except TypeError as e:
<code>
Conclusion
TypeError: can only concatenate str (not “int”) to str is an easy error to recover from. Often novice programmers starting their journey can encounter it. Languages like JavaScript have type coercion, which is helpful in some cases. However, it can be frustrating too. In addition, we looked at ways to resolve this type of error. Hoping this article resolved your issue and you learned something new today.
Trending Python Articles
-
“Other Commands Don’t Work After on_message” in Discord Bots
●February 5, 2023
-
Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials
by Rahul Kumar Yadav●February 5, 2023
-
[Resolved] NameError: Name _mysql is Not Defined
by Rahul Kumar Yadav●February 5, 2023
-
Best Ways to Implement Regex New Line in Python
by Rahul Kumar Yadav●February 5, 2023
Your Python program crashed and displayed a traceback like this one:
Traceback (most recent call last):
File "copyright.py", line 4, in <module>
statement = "Copyright " + year
TypeError: can only concatenate str (not "int") to str
Or maybe you saw a variation on that message:
Traceback (most recent call last):
File "names.py", line 3, in <module>
print("Hello" + names)
TypeError: can only concatenate str (not "list") to str
Or you may have seen a different error message that mentions + and int and str:
Traceback (most recent call last):
File "add.py", line 5, in <module>
print(start + amount)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
What do these mean?
And how can you fix your code?
What does that error message mean?
The last line is in a Python traceback message is the most important one.
TypeError: can only concatenate str (not "int") to str
That last line says the exception type (TypeError) and the error message (can only concatenate str (not "int") to str).
This error message says something similar:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Both of these error messages are trying to tell us that we’re trying to use the + operator (used for string concatenation in Python) between a string and a number.
You can use + between a string and a string (to concatenate them) or a number and a number (to add them).
But in Python, you cannot use + between a string and a number because Python doesn’t do automatic type coercion.
Type conversions are usually done manually in Python.
How do we fix this?
How we fix this will depend on our needs.
Look at the code the error occurred on (remember that tracebacks are read from the bottom-up in Python).
File "copyright.py", line 4, in <module>
statement = "Copyright " + year
Ask yourself «what am I trying to do here?»
You’re likely either trying to:
- Build a bigger string (via concatenation)
- Add two numbers together
- Use
+in another way (e.g. to concatenate lists)
Once you’ve figured out what you’re trying to do, then you’ll then need to figure out how to fix your code to accomplish your goal.
Converting numbers to strings to concatenate them
If the problematic code is meant to concatenate two strings, we’ll need to explicitly convert our non-string object to a string.
For numbers and many other objects, that’s as simple as using the built-in str function.
We could replace this:
statement = "Copyright " + year
With this:
statement = "Copyright " + str(year)
Though in many cases it may be more readable to use string interpolation (via f-strings):
statement = f"Copyright {year}"
This works because Python automatically calls the str function on all objects within the replacement fields in an f-string.
Converting other objects to strings
Using the str function (or an f-string) will work for converting a number to a string, but it won’t always produce nice output for other objects.
For example when trying to concatenate a string and a list:
>>> names = ["Judith", "Andrea", "Verena"]
>>> user_message = "Users include: " + names
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "list") to str
You might think to use str to convert the list to a string:
>>> user_message = "Users include: " + str(names)
This does work, but the resulting string might not look quite the way you’d expect:
>>> print(user_message)
Users include: ['Judith', 'Andrea', 'Verena']
When converting a list to a string you’ll likely want to join together the list items using the string join method.
>>> user_message = "Users include: " + ", ".join(names)
>>> print(user_message)
Users include: Judith, Andrea, Verena
Other types of objects may require a different approach: the string conversion technique you use will depend on the object you’re working with and how you’d like it to look within your string.
Converting strings to numbers to add them
What if our code isn’t supposed to concatenate strings?
What if it’s meant to add numbers together?
If we’re seeing one of these two error messages while trying to add numbers together:
TypeError: can only concatenate (not "int") to strTypeError: unsupported operand type(s) for +: 'int' and 'str'
That means one of our «numbers» is currently a string!
This often happens when accepting a command-line argument that should represent a number:
$ python saving.py 100
Traceback (most recent call last):
File "saving.py", line 7, in <module>
total += sys.argv[1]
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
Command-line arguments are often an issue because all command-line arguments come into Python as strings.
So the sys.argv list in that saving.py program might look like this:
>>> sys.argv
['saving.py', '100']
Note: If command-line arguments are the issue, you may want to look into using argparse to parse your command-line arguments into the correct types.
This numbers-represented-as-strings issue can also occur when prompting the user with the built-in input function.
>>> total = 0
>>> user_input = input("Also add: ")
Also add: 100
>>> total += user_input
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
The input function stores everything the user entered into a string:
Regardless of how it happened, if you want to convert your string which represents a number to an actual number, you can use either the built-in float function or the built-in int function:
>>> user_input
'100'
>>> deposit = float(user_input)
>>> deposit
100.0
>>> deposit = int(user_input)
>>> deposit
100
The float function will accept numbers with a decimal point.
The int function will only accept integers (numbers without a decimal point).
Remember: type conversions usually need to be explicit
That can only concatenate str (not "int") to str error message shows up frequently in Python because Python does not have type coercion.
Whenever you have a string and a non-string and you’d like to either sum them with + or concatenate them with +, you’ll need to explicitly convert your object to a different type.
All data that comes from outside of your Python process starts as binary data (bytes) and Python typically converts that data to strings.
Whether you’re reading command-line arguments, reading from a file, or prompting a user for input, you’ll likely end up with strings.
If your data represents something deeper than a string, you’ll need to convert those strings to numbers (or whatever type you need):
>>> c = a + int(b)
>>> a, b, c
(3, '4', 7)
Likewise, if you have non-strings (whether numbers, lists, or pretty much any other object) and you’d like to concatenate those objects with strings, you’ll need to convert those non-strings to strings:
>>> year = 3000
>>> message = "Welcome to the year " + str(year) + "!"
>>> print(message)
Welcome to the year 3000!
Though remember that f-strings might be a better option than concatenation:
>>> year = 3000
>>> message = f"Welcome to the year {year}!"
>>> print(message)
Welcome to the year 3000!
And remember that friendly string conversions sometimes require a bit more than a str call (e.g. converting lists to strings).
Table of Contents
Hide
- What is TypeError: can only concatenate str (not “int”) to str
- Example Scenario
- How to fix TypeError: can only concatenate str (not “int”) to str
- Solution
- Conclusion
In Python, we can concatenate values if they are of the same type. Let’s say if you concatenate a string and an integer you will get TypeError: can only concatenate str (not “int”) to str
In this article, we will take a look at what TypeError: can only concatenate str (not “int”) to str means and how to resolve this error with examples.
Unlike other programming languages like JavaScript, Python does not allow concatenating values of different types. For Example, we cannot concatenate a string and an integer, string and a list etc.
Example Scenario
Let us take a simple example to reproduce this issue.
product = {
"item": "iPhone",
"price": 1599,
"qty_available": 40
}
print("We have total " + product["qty_available"] + " quantities of Product " + product["item"])
Output
Traceback (most recent call last):
File "c:PersonalIJSCodemain.py", line 7, in <module>
print("We have total" + product["qty_available"] + "quantities of " + product["item"])
TypeError: can only concatenate str (not "int") to str
When we run our code we get TypeError: can only concatenate str (not “int”) to str because we are trying to concatenate the string and integer value in our print statement.
How to fix TypeError: can only concatenate str (not “int”) to str
In Python, you should ensure that the values are of the same type before performing the concatenation. Usually, we come under into this situation often during computational or printing the dictionary value using the print statement.
In the above dictionary, the product[qty_available] is of type integer and we are concatenating the integer value with strings in the print statement which leads into TypeError: can only concatenate str (not “int”) to str.
Solution
Now that we know why the issue occurs in the first place the solution is pretty simple and straightforward.
We can resolve the issue by converting the value product[qty_available] to a string before concatenating with other strings in the print statement.
Let us modify the above example and run it once again.
product = {
"item": "iPhone",
"price": 1599,
"qty_available": 40
}
print("We have total " + str(product["qty_available"]) + " quantities of Product " + product["item"])
Output
We have total 40 quantities of Product iPhone
Conclusion
The TypeError: can only concatenate str (not “int”) to str mainly occurs if you try to concatenate integer with a string. Python does not allow concatenating values of different types. We can resolve the issue by converting the integer values to strings before concatenating them in the print statement.
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
Table of Contents
- ❖ What is “TypeError” in Python?
- ❖ What does TypeError: can only concatenate str (not “int”) to str mean ?
- ◈ Solution 1: Use Same Data Types
- ◈ Solution 2: Typecasting The Data Types to Concatenate/Add Similar Types
- ◈ Solution 3: Using The format() Function
- ◈ Solution 4: Using The join() and str() Function Together
- ◈ Solution 5: Use Function
- Conclusion
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:
|
print(’10’+5) # expected output: 15 print(‘Java’ + ‘2’ + ‘Blog’) # expected output: Java2Blog |
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.
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 |
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:
|
print(10 + 5) # expected output: 15 print(‘Java’ + ‘2’ + ‘Blog’) # expected output: Java2Blog |
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‘.
|
print(int(’10’) + 5) # expected output: 15 print(‘Java’ + str(2) + ‘Blog’) # expected output: Java2Blog |
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:
|
a = «John» b = 13 print(«{} {}».format(a, b)) |
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.
|
a = [0, 1, 2] x = ‘-‘.join ((str(n) for n in a)) print(x) |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
def convert(a, b, type_): a = type_(a) b = type_(b) return a, b x, y = convert(‘Python’, 3.18, str) print(‘First: Converting To String’) print(type(x)) print(type(y)) print(«Output: «, x + » « + y) a, b = convert(’10’, 5, int) print(‘n Second: Converting To Integer’) print(type(a)) print(type(b)) print(«Output: «, a + b) |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
def convert(list1, type_): for x in range(len(list1)): list1[x] = type_(list1[x]) a = 20 b = ’25’ c = ’43’ list2 = [a, b, c] print(‘n String values:’) convert(list2, str) print([type(number) for number in list2]) print(list2) print(‘n Integer values:’) convert(list2, int) print([type(number) for number in list2]) print(list2) print(list2[0] + list2[1]) |
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.
In this article, we’ll talk about solutions of the «TypeError: can only concatenate str (not «int») to str issue appears» issue.
Before starting, you need to know that issue appears when you try to concatenate a string with an integer.
For example:
num = 99
concatenate = "python" + num
print(concatenate)
Output:
Traceback (most recent call last):
File "test.py", line 5, in <module>
concatenate = "python" + num
TypeError: can only concatenate str (not "int") to str
To solve this issue, we’ll use five methods.
Using str() method
The str() method converts the given value to a string.
How to use it:
str(num)
Example:
num = 99
concatenate = "python" + str(num)
print(concatenate)
Output:
python99
Using fstring function
f-string() inserts a variable into a string, and we’ll use it to solve the issue.
Note: this method works on Python >= 3.6.
Example:
num = 99
concatenate = f"python{num}"
print(concatenate)
Output:
python99
Using .format() function
theformat() function doing the same thing as f-string().
Example:
num = 99
concatenate = "python{}".format(num)
print(concatenate)
Output:
python99
Using the «%» symbol
You can also use the«%» symbol methods to concatenate a string with an integer.
Example:
num = 99
concatenate = "python%s"%num
print(concatenate)
Output:
python99












![[Resolved] NameError: Name _mysql is Not Defined](https://www.pythonpool.com/wp-content/uploads/2023/01/nameerror-name-_mysql-is-not-defined-300x157.webp)


