Python: how to join entries in a set into one stri

2019-01-22 05:43发布

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?

8条回答
淡お忘
2楼-- · 2019-01-22 05:49

I wrote a method that handles the following edge-cases:

  • Set size one. A ", ".join({'abc'}) will return "a, b, c". My desired output was "abc".
  • Set including integers.
  • Empty set should returns ""
def set_to_str(set_to_convert, separator=", "):
        set_size = len(set_to_convert)
        if not set_size:
            return ""
        elif set_size == 1:
            (element,) = set_to_convert
            return str(element)
        else:
            return separator.join(map(str, set_to_convert))
查看更多
家丑人穷心不美
3楼-- · 2019-01-22 05:53

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)
查看更多
在下西门庆
4楼-- · 2019-01-22 05:53

You have the join statement backwards try:

print ', '.join(set_3)
查看更多
Fickle 薄情
5楼-- · 2019-01-22 05:55

The join is called on the string:

print ", ".join(set_3)
查看更多
对你真心纯属浪费
6楼-- · 2019-01-22 05:55

I think you just have it backwards.

print ", ".join(set_3)
查看更多
Deceive 欺骗
7楼-- · 2019-01-22 05:56
', '.join(set_3)

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

查看更多
登录 后发表回答