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?
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)
来源:https://stackoverflow.com/questions/8704952/how-to-convert-a-tuple-to-a-string-in-python