Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join entries in a set into one string?

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?

like image 809
Spencer Avatar asked Sep 06 '11 17:09

Spencer


People also ask

How do you join a set of strings?

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.

How do I join a list of elements into a 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() .

How do you join set elements in Python?

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.


2 Answers

', '.join(set_3) 

The join is a string method, not a set method.

like image 137
Jmjmh Avatar answered Oct 19 '22 22:10

Jmjmh


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) 
like image 35
Jack Edmonds Avatar answered Oct 20 '22 00:10

Jack Edmonds