8
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
  • 38,994
  • 14
  • 83
  • 119
karan_s438
  • 1,353
  • 1
  • 9
  • 15

3 Answers3

8

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.

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
6

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'
>>>
Praveen
  • 8,945
  • 4
  • 31
  • 49
  • 1
    This answer generalizes well for tuples with length > 1. – sirfz Dec 06 '16 at 11:23
  • not sure if @Chris_Rands answer is a better one. This answer and his answer both work for me! – karan_s438 Dec 06 '16 at 11:33
  • @JackSparrow these days itertools is the recommended way to flatten lists or tuples http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python – Chris_Rands Dec 06 '16 at 11:49
-1
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
BPL
  • 9,632
  • 9
  • 59
  • 117