Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Khamkéo Vilaysing
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.
Here is an example of how the error occurs.
my_str = 'fruits: ' my_set = {'apple', 'banana', 'kiwi'} # ⛔️ TypeError: can only concatenate str (not "set") to str print(my_str + my_set)
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.
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.
my_str = 'fruits:' my_set = {'apple', 'banana', 'kiwi'} result = f'{my_str} {my_set}' print(result) # 👉️ fruits: {'kiwi', 'apple', 'banana'}
f
.Make sure to wrap expressions in curly braces - {expression}
.
If you need to add an item to the set, use the add()
method.
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.
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.
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.