Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

mysql - Python: Convert tuple to comma separated String

import MySQLdb

db = MySQLdb.connect("localhost","root","password","database")
cursor = db.cursor()
cursor.execute("SELECT id FROM some_table")
u_data = cursor.fetchall()

>>> print u_data
((1320088L,),)

What I found on internet got me till here:

string = ((1320088L,),)
string = ','.join(map(str, string))
>>> print string
(1320088L,)

what I expect output to look like:

 #Single element expected result
 1320088L  
 #comma separated list if more than 2 elements, below is an example
 1320088L,1320089L
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use itertools.chain_fromiterable() to flatten your nested tuples first, then map() to string and join(). Note that str() removes the L suffix because the data is no longer of type long.

>>> from itertools import chain
>>> s = ((1320088L,),)
>>> ','.join(map(str,chain.from_iterable(s)))
'1320088'

>>> s = ((1320088L,1232121L),(1320088L,),)
>>> ','.join(map(str,chain.from_iterable(s)))
'1320088,1232121,1320088'

Note, string is not a good variable name because it is the same as the string module.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...