Joining elements of a list

前端 未结 4 1980
旧巷少年郎
旧巷少年郎 2020-12-20 08:21

I have a list of tuples like:

data = [(\'a1\', \'a2\'), (\'b1\', \'b2\')]

And I want to generate a string like this: \"(\'a1\', \'a2\

相关标签:
4条回答
  • 2020-12-20 08:59

    Discard the opening and closing brackets from str() output:

    >>> data = [('a1', 'a2'), ('b1', 'b2')]
    >>> str(data)
    "[('a1', 'a2'), ('b1', 'b2')]"
    >>> str(data)[1:-1]
    "('a1', 'a2'), ('b1', 'b2')"
    >>> 
    
    0 讨论(0)
  • 2020-12-20 09:00

    The answers by payne and marcog are correct, as they directly convert the tuple to a string.

    If you need more flexibility with the output format, you can unpack the tuple inside the generator expression and use its values as parameters to a format string in this way:

        ", ".join("first element: %s, second element: %s" % (str(x), str(y)) for x, y in data)
    

    In this way you can overcome the default str representation of a tuple.

    0 讨论(0)
  • 2020-12-20 09:09

    Use a generator to cast the tuples to strings and then use join().

    >>> ', '.join(str(d) for d in data)
    "('a1', 'a2'), ('b1', 'b2')"
    
    0 讨论(0)
  • 2020-12-20 09:11
    ','.join(str(i) for i in data)
    
    0 讨论(0)
提交回复
热议问题