Cookie Policy

We use cookies to operate this website, improve usability, personalize your experience, and improve our marketing. Privacy Policy.

By clicking "Accept" or further use of this website, you agree to allow cookies.

Accept
Learn Machine Learning by Doing Learn Now
You are reading solutions / Python
alfie-grace-headshot-square2.jpg
Author: Alfie Grace
Data Scientist

TypeError: can only concatenate str (not "int") to str

TypeError: can only concatenate str (not "int") to str

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:

result = 4961 // 342

print('The result is : ' + result)
Out:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-4458afcb9bfc> in <module>
      1 result = 4961 // 342
      2 
----> 3 print('The result is : ' + result)

TypeError: can only concatenate str (not "int") to str

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:

  1. Convert the integer variable to a string before concatenating
  2. Use a comma in the print() statement to concatenate
  3. Use an f'' string (f-string).

Each of these are demonstrated below.

Solution

result = 4961 // 342

# 1
print('The result is: ' + str(result))

# 2
print('The result is:', result)

# 3
print(f'The result is: {result}')
Out:
The result is: 14
The result is: 14
The result is: 14

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:

salary_dict = {
    'Junior Data Scientist' : 80, 
    'Senior Data Scientist' : 120, 
    'Lead Data Engineer' : 140,
}

for employee, salary in salary_dict.items():
    print('Position: ' + employee + ' Salary: $' + salary + '000')
Out:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-0b430355c9a3> in <module>
      6 
      7 for employee, salary in salary_dict.items():
----> 8     print('Position: ' + employee + ' Salary: $' + salary + '000')

TypeError: can only concatenate str (not "int") to str

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

salary_dict = {
    'Junior Data Scientist' : 80, 
    'Senior Data Scientist' : 120, 
    'Lead Data Engineer' : 140,
}

for employee, salary in salary_dict.items():
    print(f'Position: {employee}, Salary: ${salary}000')
Out:
Position: Junior Data Scientist, Salary: $80000
Position: Senior Data Scientist, Salary: $120000
Position: Lead Data Engineer, Salary: $140000

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.

with open('x_power_values.csv', 'w') as f:
    
    # Write CSV header row
    f.write('x,x_squared,x_cubed\n')
    
    for x in range(1,1001):
        x_squared = x**2
        x_cubed = x**3
        file_row = str(x) + ',' + x_squared + ',' + x_cubed + '\n'
        f.write(file_row)
Out:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-0311bccc0432> in <module>
      7         x_squared = x**2
      8         x_cubed = x**3
----> 9         file_row = str(x) + ',' + x_squared + ',' + x_cubed + '\n'
     10         f.write(file_row)
TypeError: can only concatenate str (not "int") to str

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

with open('x_power_values.csv', 'w') as f:
    
    # Write CSV header row
    f.write('x,x_squared,x_cubed\n')
    
    for x in range(1,1001):
        x_squared = x**2
        x_cubed = x**3
        file_row = f'{x},{x_squared},{x_cubed}\n'
        f.write(file_row)

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.


Meet the Authors

alfie-grace-headshot-square2.jpg

Alfie graduated with a Master's degree in Mechanical Engineering from University College London. He's currently working as Data Scientist at Square Enix. Find him on LinkedIn.

Brendan Martin
Editor: Brendan
Founder of LearnDataSci

Get updates in your inbox

Join over 7,500 data science learners.