Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - convert list of tuples to string

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?

like image 537
ssoler Avatar asked Sep 05 '25 16:09

ssoler


2 Answers

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

like image 78
mykhal Avatar answered Sep 07 '25 16:09

mykhal


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)
like image 25
polygenelubricants Avatar answered Sep 07 '25 17:09

polygenelubricants