How to convert a tuple to a string in Python?

After the MySQL select statement, I leave 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 ',)]) 

I would like to have

 emaillist = "\n".join(queryresult) 

at the end, enter the line:

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

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

+4
source share
4 answers

So far, you are sure that you have only one element per tuple:

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

Try it 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. A join can only work with strings, but tuple elements are set elements. To make the connection work, you need to iterate over the set to convert each element to a string. Finally, once you are done, you can join them as your heart desires.

On a side note. The round way :-)

 >>> 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 
+2
source

Understanding Lists in Strings

 [item[0] for item in queryresult] 

should help. eg,

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

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


change

Generator expression is even better:

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

thanks @delnan for this update

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

Source: https://habr.com/ru/post/1388977/


All Articles