TypeError: can only concatenate str (not "int") to str
LearnDataSci is reader-supported. When you purchase through links on our site, earned commissions help support our team of writers, researchers, and designers at no extra cost to you.
Why does this occur?
This error occurs when you try adding (concatenating) an integer to a string. This error happens most commonly when trying to print an integer variable or writing information to a file. You would also get this error when adding a float or list to a string or other data types.
Types in Python have various associated methods, which restrict what you can or can't do with that specific data type. Some of the main types which you may have encountered so far are strings, integers, and floats.
In this lesson, we'll focus on strings and considering some examples where you may need to combine numbers with your string to display information effectively.
Cause 1: Printing Computation Results
In this example, let's say you've just discovered the //
operator, which divides the first operand by the second and rounds the result down to the nearest integer — also known as floor division. You're interested in finding out the results given by this operator for various numbers, so you write the following script:
The script gets through the calculations but fails when we try to combine our result with the text in result_string
. This failure occurs because the concatenate operator (+) for strings in Python doesn't know how to comvert convert numeric types to strings implicitly.
There are three straightforward solutions:
- Convert the integer variable to a string before concatenating
- Use a comma in the
print()
statement to concatenate - Use an
f''
string (f-string).
Each of these are demonstrated below.
Solution
In option one, by applying the str()
function to our result
variable, we converted the result
variable from an int
to a str
, converting from 14 to '14'. Similarly, if we wanted to convert our variable back into an integer or a float instead, we could use the functions int()
or float()
to convert '14' to 14 or 14.0, respectively. The conversion from one type to another is called type casting.
Option two allows the print()
function to convert the result
to str
automatically.
Option three performs a conversion through the use of curly braces in an f-string.
Cause 2: Printing Dictionary Values
This error can also be triggered by appending values from a collection-type object to a string. Lists, tuples, and dictionaries are all examples of collection types.
Imagine you've got a dictionary of employees at Company A, describing their position and salaries (in thousands). You'd like to create a script that iterates through the employees and prints off lines representing their jobs and salaries. This information could be displayed as follows:
Taking a look at the dictionary we've used, the keys are all in string format, so Python should have no problems concatenating the employee variable to the string. The error comes from the dictionary values being integers.
We could edit the dictionary and convert these values into strings manually, but we have other options at our disposal.
Solution
As seen in the previous solution, the f-string lets us insert variables into strings without explicit conversion to str
. Even though we used an f-string here, any of the other options from above could've worked.
Cause 3: Writing Values to Files
As mentioned previously, this error can frequently occur when writing data to a file. An excellent example is writing comma-separated-values (CSV) files for data analysis (much easier in pandas).
You could do this by generating all your values in a context manager and then writing them to the CSV file as you go. A script for executing this is shown below, with the script generating a CSV file called x_power_values.csv, which contains values for x, x squared, and x cubed.
Although we have converted x
from an integer to a string, x_squared
and x_cubed
are still integers as these get generated before converting x
. We can quickly fix this using one of the methods already mentioned above:
Solution
In this solution, we've utilized an f-string again. Now that Python can concatenate x_squared
and x_cubed
to the file_row
string, the CSV file can be generated successfully by the script. In a pandas DataFrame, our CSV file would look like this:
x x_squared x_cubed 0 1 1 1 1 2 4 8 2 3 9 27 3 4 16 64 4 5 25 125 .. ... ... ... 999 1000 1000000 1000000000
Summary
This error occurs when Python tries to combine conflicting data types. In this scenario, the issue was triggered by attempting to concatenate strings and integers, but a wide range of different types can cause this problem.
In many situations, we can solve the problem by converting a variable to the string type using the str()
function, using comma-separated arguments to print()
, or by using an f-string to handle the concatenation for us.