Python: how to join entries in a set into one string?

前端 未结 8 1200
青春惊慌失措
青春惊慌失措 2020-12-13 17:06

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 atte

相关标签:
8条回答
  • 2020-12-13 17:35

    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))
    
    0 讨论(0)
  • 2020-12-13 17:36

    Set's do not have an order - so you may lose your order when you convert your list into a set, i.e.:

    >>> orderedVars = ['0', '1', '2', '3']
    >>> setVars = set(orderedVars)
    >>> print setVars
    ('4', '2', '3', '1')
    

    Generally the order will remain, but for large sets it almost certainly won't.

    Finally, just incase people are wondering, you don't need a ', ' in the join.

    Just: ''.join(set)

    :)

    0 讨论(0)
提交回复
热议问题