[Solved] TypeError: can only concatenate str (not “int”) to 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.

Type error raised when adding a string to an integer
Type error raised when adding a string to an integer

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.

TypeError, can only concatenate str (not
TypeError, can only concatenate str (not “int”) to str

Why can only concatenate str (not “int”) to str

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.

Concatenating 0th and 2nd item together.
I am concatenating the 0th and 2nd items together.

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'])
Concateing name and release_yr of book throws an error
Concatenating the name and release_yr of the book throws an error

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']))
name and release year of the books
name and release year of the books

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']))
Using f-strings, format method and string formatting
Using f-strings, format method, and string formatting

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.
On concatenating string and integer columns error gets thrown
On concatenating string and integer columns, an error gets thrown

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)

Converting integer column values to string resolves the issue
Converting integer column values to strings resolves the issue

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.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments