How to convert a tuple to a string in Python?

早过忘川 提交于 2019-12-05 16:43:14

As long as you're sure you have just one element per tuple:

'\n'.join(elem[0] for elem in queryresult)

A list comprehension along the lines of

[item[0] for item in queryresult]

should help. eg,

emaillist = "\n".join([item[0] for item in queryresult])

.. this makes strong assumptions about the type and structure of queryresult, however.


edit

A generator expression is even better at doing this:

emaillist = "\n".join(item[0] for item in queryresult)

thanks to @delnan for this update

Try this and see

>>> something=set([('1@a.com',), ('2@b.net',), ('3@c.com',), ('4@d.com',), ('5@e.com',), ('6@f.net',), ('7@h.net',), ('8@g.com',)])
>>> print '\n'.join(''.join(s) for s in something)
6@f.net
7@h.net
2@b.net
1@a.com
8@g.com
5@e.com
4@d.com
3@c.com

Note, join can only work on strings, but the items of the set are tuples. To make the join work, you have to iterate over the set to convert each item as string. Finally once done you can join them in the way your heart desires

On a side note. A circumbendibus way of doing it :-)

>>> print "\n".join(re.findall("\'(.*?)\'",pprint.pformat(something)))
1@a.com
2@b.net
3@c.com
4@d.com
5@e.com
6@f.net
7@h.net
8@g.com
new = '\n'.join(x[0] for x in old)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!