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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: can only concatenate str (not "set") to str #

The Python "TypeError: can only concatenate str (not "set") to str" occurs when we try to concatenate a string and a set. To solve the error, use a formatted string literal, or use the add() method to add an item to the set.

typeerror can only concatenate str not set to str

Here is an example of how the error occurs.

main.py
my_str = 'fruits: ' my_set = {'apple', 'banana', 'kiwi'} # ⛔️ TypeError: can only concatenate str (not "set") to str print(my_str + my_set)
We tried to use the addition (+) operator to concatenate a string and a set which caused the error.

The values on the left and right-hand sides need to be of compatible types.

If you only need to print the contents of the set, use a comma between the string and the set.

main.py
my_str = 'fruits: ' my_set = {'apple', 'banana', 'kiwi'} # 👇️ fruits: {'apple', 'kiwi', 'banana'} print(my_str, my_set)

Alternatively, you can use a formatted string literal.

main.py
my_str = 'fruits:' my_set = {'apple', 'banana', 'kiwi'} result = f'{my_str} {my_set}' print(result) # 👉️ fruits: {'kiwi', 'apple', 'banana'}
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

Make sure to wrap expressions in curly braces - {expression}.

If you need to add an item to the set, use the add() method.

main.py
my_str = 'fruits: ' my_set = {'apple', 'banana', 'kiwi'} my_set.add('melon') # 👇️ {'kiwi', 'banana', 'apple', 'melon'} print(my_set)

The set.add method adds the provided element to the set.

You can also pass the set to the str() class to convert it to a string before concatenating the two strings.

main.py
my_str = 'fruits: ' my_set = {'apple', 'banana', 'kiwi'} result = my_str + str(my_set) # 👇️ fruits: {'kiwi', 'apple', 'banana'} print(result)

If you aren't sure what type a variable stores, use the built-in type() class.

main.py
my_str = 'fruits: ' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ True my_set = {'apple', 'banana', 'kiwi'} print(type(my_set)) # 👉️ <class 'set'> print(isinstance(my_set, set)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

Conclusion #

The Python "TypeError: can only concatenate str (not "set") to str" occurs when we try to concatenate a string and a set. To solve the error, use a formatted string literal, or use the add() method to add an item to the set.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.