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
Chris_Rands
41.7k15 gold badges92 silver badges126 bronze badges
asked Dec 6, 2016 at 11:12
karan_s438
1,3691 gold badge9 silver badges15 bronze badges
3 Answers 3
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.
answered Dec 6, 2016 at 11:23
Chris_Rands
41.7k15 gold badges92 silver badges126 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
I think the string is a tuple of tuple containing long values.
>>> string = ((1320088L,),)
>>> ','.join(str(y) for x in string for y in x if len(x) > 0)
'1320088'
>>>
e.g. with more than one value
>>> string = ((1320088L,1232121L),(1320088L,),)
>>> ','.join(str(y) for x in string for y in x if len(x) > 0)
'1320088,1232121,1320088'
>>>
answered Dec 6, 2016 at 11:20
Praveen
9,4634 gold badges38 silver badges51 bronze badges
3 Comments
sirfz
This answer generalizes well for tuples with length > 1.
karan_s438
not sure if @Chris_Rands answer is a better one. This answer and his answer both work for me!
Chris_Rands
@JackSparrow these days itertools is the recommended way to flatten lists or tuples stackoverflow.com/questions/952914/…
string = ((1320088L,),)
print(','.join(map(str, list(sum(string, ())))))
string = ((1320088L, 1232121L), (1320088L,),)
print(','.join(map(str, list(sum(string, ())))))
Output:
1320088
1320088,1232121,1320088
answered Dec 6, 2016 at 11:37
BPL
10k12 gold badges69 silver badges136 bronze badges
Comments
Explore related questions
See similar questions with these tags.
default