Python - convert list of tuples to string

╄→гoц情女王★ 提交于 2019-11-27 20:39:15

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)

How about:

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

How about

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

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.

The most pythonic solution is

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

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

result = ', '.join(tuple_strings)

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)'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!