Python TypeError: can only concatenate str (not “int”) to str Solution

by | Data Science, Programming, Python, Tips

If we try to concatenate an integer with a string, we will raise the error “TypeError: can only concatenate str (not “int”) to str”. This error occurs because you can only concatenate strings with other strings.

In this tutorial, we will go through the error in detail and go through examples to learn how to solve it.


Why does this TypeError Occur?

This error occurs you try to concatenate an integer to a string. Likely, you will encounter this error when printing an integer variable or writing data to a file. Let’s look at several examples of correct concatenation then an incorrect example.

# Correct Example 
print(1+4)
print('darth ' + 'vader')
print('go ' * 3)
# Incorrect Example
print('Love ' + 2 + 'Learn')

Output:

5
darth vader
go go go
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-f889382ef282> in <module>
----> 1 print('Love ' + 2 + ' Learn')
TypeError: can only concatenate str (not "int") to str

The first three lines of code work because we either concatenate between the same types or multiply between an integer and a string, which is allowed in Python. Python is a dynamic programming language. It executes the code line by line then throws the TypeError, because concatenating a string and a numeric value (int) is not allowed in Python.

Python does not know how to convert numeric types to strings implicitly. We can convert integers to string using the built-in str() method.

Generally, TypeErrors occur when you attempt to perform an illegal operation for a specific data type. Another example of an illegal operation is attempting to call a NoneType value as a function, which raises the ‘nonetype’ object is not callable error.

Solution to Concatenating String and Integer

There are five solutions we can apply to print out the combination of a string and an integer:

  • Convert the integer to a string using str() before concatenating. The conversion from one type to another is called type casting.
  • Use a comma in the print statement
  • Use an f” string, which is a way to embed expressions inside string literals, using a minimal syntax. An f-string is an expression evaluated at run time, not a constant value.
  • Using the format() function, which joins various elements inside a string through positional formatting.
  • Create a conversion function that converts a variable from one type to another.
# str() solution
print('Love ' + str(2) + ' Learn')
# comma solution
print('Love' , 2 , 'Learn')
# f string solution
print(f'Love {2} Learn')
# format() solution
a = 'Love'
b = 2
c = 'Learn'
print('{} {} {}'.format(a,b,c)
# function method
def convert(a, b, c, type_):
    a=type_(a)
    b=type_(b)
    c=type_(c)
    return a, b, c
a, b, c = convert('Love ', 2, ' Learn', str)
print(a + b + c )

Output:

Love 2 Learn
Love 2 Learn
Love 2 Learn
Love 2 Learn
Love 2 Learn

Solution to Printing Dictionary Values

The error can also occur when trying to append values from a collection-type object – for example, Lists, tuples, and dictionaries – to a string. Let’s look at an example of a dictionary, where we have the top three grossing films of 2021 and the amount in millions of dollars. If we want to create a script that iterates through the movie and print off the names and the gross amount, we can do this as follows:

films = {
    'Shang-Chi and the Legend of the Ten Rings' : 224,
    'Venom: Let There Be Carnage' : 210,
    'Black Widow' : 184
}
for film, gross in films.items():
    print('Film name:  ' + film + ' Gross: $' + gross + '000000')

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-44434750f988> in <module>
      1 for film, gross in films.items():
----> 2     print('Film name:  ' + film + ' Gross: $' + gross + '000000')
      3 
TypeError: can only concatenate str (not "int") to str

The keys are in string format. However, the dictionary values, or the gross, are integers. We can use one of the solutions above to access the dictionary values and concatenate them to the film names.

for film, gross in films.items():
    print(f'Film name: {film}, Gros: ${gross}000000')

Output:

Film name: Shang-Chi and the Legend of the Ten Rings, Gros: $224000000
Film name: Venom: Let There Be Carnage, Gros: $210000000
Film name: Black Widow, Gros: $184000000

The use of f-string allows us to insert non-string type variables without explicitly converting them to str. We could use any of the other options.

Solution to Writing Values to Files

Data scientists typically use comma-separated-values (CSV) files to store data as they can be read easily with Pandas. Writing data to file is prone to errors. Let’s look at an example of generating values and storing them in a CSV file. Our script will generate a CSV file called squares_and_square_root_values.csv, calculate several squares and square roots, and write to the file. See my blog post titled “Python Square Root” for information on calculating the square root.

import math
with open('squares_and_square_root_values.csv', 'w') as f:
    f.write('x, x_squared, sqrt(x)\n')

    for x in range(4, 121):
        x_squared = x ** 2
        sqrt_x = math.sqrt(x)
        file_row = str(x) + ', ' + x_squared + ',' + sqrt_x + '\n'
        f.write(file_row)

Output:

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

We can solve this by using one of our solutions. Although we converted x from an integer to a string, x_squared and sqrt_x are still integers, and we generate these values before converting x. We can convert these values to strings as well.

with open('squares_and_square_root_values.csv', 'w') as f:
    f.write('x, x_squared, sqrt(x)\n')
    for x in range(4, 121):
        x_squared = x ** 2
        sqrt_x = math.sqrt(x)
        file_row = str(x) + ', ' + str(x_squared) + ',' + str(sqrt_x) + '\n'
        f.write(file_row)

Python can concatenate the values and write them to the generated CSV file with the integers correctly converted to strings. You can use Pandas to read the CSV file and check the values as follows:

import pandas
# Ensure you are in the same directory as where you saved the CSV file 
df = pd.read_csv('squares_and_square_root_values.csv')
df

Output:

 x   x_squared    sqrt(x)
0      4          16   2.000000
1      5          25   2.236068
2      6          36   2.449490
3      7          49   2.645751
4      8          64   2.828427
..   ...         ...        ...
112  116       13456  10.770330
113  117       13689  10.816654
114  118       13924  10.862780
115  119       14161  10.908712
116  120       14400  10.954451
[117 rows x 3 columns]

For more information on Pandas, you can go to my beginner tutorial for Pandas.

Summary

This TypeError occurs when Python tries to combine mismatching data types. In this case, the error is specifically for concatenating strings and integers, but a wide variety of types could cause this problem. We have seen the basics of the int and str types in Python and the various solution we can use to concatenate the two types to avoid the TypeError. The most straightforward approach is to typecast any integers to string. You can also use comma-separated arguments or use f-string to handle the concatenation. If you want a more hands-on approach, you can create your function that takes in the variables and the type you want to cast and returns the converted variables.

For further reading on concatenation in Python, go to the articles:

For further reading on using arithmetic operators on strings and integers, go to the article: “How to Solve Python TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’“.

Thank you for reading to the end of this article.

You can find other tips such as checking if a file exists and solutions to common TypeErrors, such as list indices must be integers or slices, not str, can’t multiply sequence by non-int of type ‘float’ and ValueErrors such as invalid literal for int() with base 10.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨