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), (
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
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)
The most pythonic solution is
tuples = [(1, 2), (3, 4)]
tuple_strings = ['(%s, %s)' % tuple for tuple in tuples]
result = ', '.join(tuple_strings)
How about
l = [(1, 2), (3, 4)]
print repr(l)[1:-1]
# (1, 2), (3, 4)
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.
How about:
>>> tups = [(1, 2), (3, 4)]
>>> ', '.join(map(str, tups))
'(1, 2), (3, 4)'