In this tutorial, we will learn how to solve the Python TypeError: can only concatenate str (not “int”) to str. The error occurs when the + operator is used to join a string with an integer without converting one of the values first.
What does “can only concatenate str (not int) to str” mean in Python?
In Python, + has different meanings depending on the operands. With two strings, it concatenates them. With two numbers, it performs addition. Python does not automatically decide how to combine a str and an int, so an expression such as "Year: " + 2020 raises a TypeError.
"Hello " + "Python" # valid: str + str
10 + 20 # valid: int + int
"Year: " + 2020 # TypeError: str + int
Reproducing the Python str and int concatenation error
As the error message says, in Python, you can only concatenate string to string. But, if you got this message, may be, you are trying to concatenate an integer to a string.
In the following example, we shall recreate the above error, and discuss on what went wrong in the eyes of Python.
site = 'www\.tutorialkart.com'
year = 2020
print(string + integer)
Note: The legacy snippet above declares site and year but then refers to string and integer. As written, that exact snippet raises a NameError. The intended TypeError example is the same operation using the declared variables, as shown below.
site = 'www.tutorialkart.com'
year = 2020
print(site + year)
If you run the above Python program, you will get the following output in Python terminal.
Traceback (most recent call last):
File "d:/workspace/fipics/rough.py", line 3, in <module>
print(string+integer)
TypeError: can only concatenate str (not "int") to str
The traceback shown above represents the same type mismatch: Python is being asked to concatenate a string and an integer. The exact wording of a traceback can vary by Python version and by the variable names used in your program.
Why Python rejects str + int
The datatype of variable site is string and that of year is integer. Let us check that programmatically.
Python Program
site = 'www\.tutorialkart.com'
year = 2020
print(type(site))
print(type(year))
Output
<class 'str'>
<class 'int'>
Yeah! As the Python interpreter is saying, we are trying to concatenate string and integer.
String concatenation requires both operands to be strings. Therefore, if the integer is meant to become part of text, convert it to str. If the values are meant to be added numerically, convert the string to a numeric type instead.
Fix “can only concatenate str (not int) to str” with str()
So, how do we solve this issue and print a number along with the string or concatenate the number to a string.
Convert the integer to a string using string class str().
In the following example, we shall concatenate the integer to string by converting the integer to a string.
site = 'www\.tutorialkart.com'
year = 2020
print(site+str(year))
Run the above Python program, and the program shall run without any errors.
www\.tutorialkart.com2020
If you want a separator between the text and number, include it in one of the strings.
site = 'www.tutorialkart.com'
year = 2020
message = site + ' - ' + str(year)
print(message)
www.tutorialkart.com - 2020
Use an f-string instead of manual str and int concatenation
When the goal is to insert an integer into readable text, an f-string is usually clearer than repeatedly calling str(). Put an f before the string and place the variable inside braces.
site = 'www.tutorialkart.com'
year = 2020
print(f'{site} - {year}')
www.tutorialkart.com - 2020
An f-string formats the integer as part of the resulting string, so there is no str + int operation to trigger the error.
Print strings and integers without concatenating them
If you only need to display values, you do not have to concatenate them. Pass multiple arguments to print(). Python converts each value for display and inserts a space between the arguments by default.
year = 2020
print('Year:', year)
Year: 2020
Convert the string to int when you actually want numeric addition
Do not always convert the integer to a string. Sometimes the real intention is arithmetic. For example, a numeric value may be stored as text. In that case, convert the string to int before adding.
count = '20'
extra = 5
total = int(count) + extra
print(total)
25
Use this approach only when the string contains a valid integer representation. For example, int("20") works, while int("twenty") raises ValueError.
Related “can only concatenate str” TypeError variants
The same rule applies when the second value is another non-string type. You may see messages mentioning float, NoneType, list, bytes, or set instead of int.
'Price: ' + 19.5 # str + float
'Value: ' + None # str + NoneType
'Items: ' + ['a', 'b'] # str + list
'Data: ' + b'abc' # str + bytes
'Tags: ' + {'python'} # str + set
For values that are simply being displayed as text, str(value) or an f-string is often appropriate. For structured values such as lists, sets, and bytes, first decide whether you really want their text representation or whether your code should process the underlying data in another way.
Check variable types before concatenating strings
If the source of the error is not obvious, inspect the values and their types immediately before the failing expression. This is especially useful when variables have passed through several functions or data-processing steps.
name = 'Items'
count = 3
print(repr(name), type(name))
print(repr(count), type(count))
'Items' <class 'str'>
3 <class 'int'>
type() tells you the datatype, while repr() makes the value easier to inspect. Once you know which operand is not a string, you can choose the correct conversion instead of applying str() blindly.
Rule for avoiding str and int concatenation errors
Concluding this Python Tutorial, please note that Python does not allow the concatenation of string with integer. And to solve this, you may have to exclusively convert the integer to a string.
In practice, choose the conversion based on what the expression is supposed to do: use str() or an f-string when creating text, use separate arguments to print() when you only need output, and use int() when the operation is supposed to be numeric addition.
TutorialKart.com