How to convert a tuple to a string in Python?

霸气de小男生 提交于 2019-12-07 07:08:26

问题


After a MySQL select statement, I am left with the following:

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

What I would like to have is a

emaillist = "\n".join(queryresult)

to in the end, have a string:

1@a.com
2@b.net
3@c.com
etc

What would be the proper way to convert this nested tuple into string?


回答1:


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

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



回答2:


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




回答3:


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



回答4:


new = '\n'.join(x[0] for x in old)


来源:https://stackoverflow.com/questions/8704952/how-to-convert-a-tuple-to-a-string-in-python

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