Python: Convert tuple to comma separated String

后端 未结 3 732
谎友^
谎友^ 2021-01-13 04:29
import MySQLdb

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


        
相关标签:
3条回答
  • 2021-01-13 05:06
    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
    
    0 讨论(0)
  • 2021-01-13 05:12

    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.

    0 讨论(0)
  • 2021-01-13 05:21

    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'
    >>>
    
    0 讨论(0)
提交回复
热议问题