25
votes

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?

7
What are these tuples for, why do they need to be in a string, and do they in fact need to be tuples? - Ignacio Vazquez-Abrams
why would you want to do this? what is your real problem? - SilentGhost
@Ignacio, @SilentGhost: I'd love to have you guys elaborate more on your comments (I'm still learning Python myself). It may not be an actual answer to OP's string formatting problem, but I'm sure you guys have very important points to make. - polygenelubricants
@polygenelubricants: Bottom line: there's no point to this. The tuple -- as a tuple -- is a fine structure. Why mess with it to make an obscurely formatted string? If all they want is a string, then the string.format method will do the job pretty simply. If they want something else, then the question should say what they're tying to accomplish. - S.Lott
Wait, what? You want to introduce SQL injection attacks into your code? Python gives you the tools to do it right and you want to go out of your way to do it wrong? I have no words. - Ignacio Vazquez-Abrams

7 Answers

34
votes

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

36
votes

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)
21
votes

How about:

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

How about

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

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.

1
votes

The most pythonic solution is

tuples = [(1, 2), (3, 4)]

tuple_strings = ['(%s, %s)' % tuple for tuple in tuples]

result = ', '.join(tuple_strings)
0
votes

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