Basically, I am trying to join together the entries in a set in order to output one string. I am trying to use syntax similar to the join function for lists. Here is my attempt:
list = ["gathi-109","itcg-0932","mx1-35316"] set_1 = set(list) set_2 = set(["mx1-35316"]) set_3 = set_1 - set_2 print set_3.join(", ")
However I get this error: AttributeError: 'set' object has no attribute 'join'
What is the equivalent call for sets?
Note: The join() method provides a flexible way to create strings from iterable objects. It joins each element of an iterable (such as list, string, and tuple) by a string separator (the string on which the join() method is called) and returns the concatenated string.
If you want to concatenate a list of numbers ( int or float ) into a single string, apply the str() function to each element in the list comprehension to convert numbers to strings, then concatenate them with join() .
Sets can be joined in Python in a number of different ways. For instance, update() adds all the elements of one set to the other. Similarly, union() combines all the elements of the two sets and returns them in a new set. Both union() and update() operations exclude duplicate elements.
', '.join(set_3)
The join
is a string method, not a set method.
Sets don't have a join
method but you can use str.join
instead.
', '.join(set_3)
The str.join
method will work on any iterable object including lists and sets.
Note: be careful about using this on sets containing integers; you will need to convert the integers to strings before the call to join. For example
set_4 = {1, 2} ', '.join(str(s) for s in set_4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With