Python – convert list of tuples to string

Each Answer to this Q is separated by one/two green lines.

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?

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)

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

How about:

>>> tups = [(1, 2), (3, 4)]
>>> ', '.join(map(str, tups))
'(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.

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


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .