Reputation: 5264
Which is the most pythonic way to convert a list of tuples to string?
I have:
[(1,2), (3,4)]
and I want:
"(1,2), (3,4)"
My solution to this has been:
l=[(1,2),(3,4)]
s=""
for t in l:
s += "(%s,%s)," % t
s = s[:-1]
Is there a more pythonic way to do this?
Upvotes: 30
Views: 67775
Reputation: 6308
I think the most Pythonic solution is
tuples = [(1, 2), (3, 4)]
tuple_strings = ['(%s, %s)' % tuple for tuple in tuples]
result = ', '.join(tuple_strings)
Upvotes: 2
Reputation: 19905
you might want to use something such simple as:
>>> l = [(1,2), (3,4)]
>>> str(l).strip('[]')
'(1, 2), (3, 4)'
.. which is handy, but not guaranteed to work correctly
Upvotes: 40
Reputation: 11
I think this is pretty neat:
>>> l = [(1,2), (3,4)]
>>> "".join(str(l)).strip('[]')
'(1,2), (3,4)'
Try it, it worked like a charm for me.
Upvotes: 1
Reputation: 361
Three more :)
l = [(1,2), (3,4)]
unicode(l)[1:-1]
# u'(1, 2), (3, 4)'
("%s, "*len(l) % tuple(l))[:-2]
# '(1, 2), (3, 4)'
", ".join(["%s"]*len(l)) % tuple(l)
# '(1, 2), (3, 4)'
Upvotes: 0
Reputation: 10162
How about:
>>> tups = [(1, 2), (3, 4)]
>>> ', '.join(map(str, tups))
'(1, 2), (3, 4)'
Upvotes: 21
Reputation: 383746
You can try something like this (see also on ideone.com):
myList = [(1,2),(3,4)]
print ",".join("(%s,%s)" % tup for tup in myList)
# (1,2),(3,4)
Upvotes: 39