ssoler
ssoler

Reputation: 5264

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?

Upvotes: 30

Views: 67775

Answers (7)

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

mykhal
mykhal

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

luissanchez
luissanchez

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

blaztinn
blaztinn

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

pillmuncher
pillmuncher

Reputation: 10162

How about:

>>> tups = [(1, 2), (3, 4)]
>>> ', '.join(map(str, tups))
'(1, 2), (3, 4)'

Upvotes: 21

polygenelubricants
polygenelubricants

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

Benj
Benj

Reputation: 1875

How about

l = [(1, 2), (3, 4)]
print repr(l)[1:-1]
# (1, 2), (3, 4)

Upvotes: 1

Related Questions