开发者

Joining elements of a list

I have a list of tuples like:

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

And I want to generate a string l开发者_开发百科ike this: "('a1', 'a2'), ('b1'. 'b2')"

If i do something like: ','.join(data), I get an error:

TypeError: sequence item 0: expected string, tuple found

If I want to do something in a single line without doing something like:

for elem in data:
  str += ',%s' % str(elem)

then is there a way?


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

>>> ', '.join(str(d) for d in data)
"('a1', 'a2'), ('b1', 'b2')"


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')"
>>> 


','.join(str(i) for i in data)


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜