>>> import MySQLdb
>>> db = MySQLdb.connect( host = "localhost", user ="root", passwd = "", db = "smoky_db" )
>>> cur = db.cursor()
>>> cur.execute( 'SELECT * FROM logs' )
3L
>>> rows = cur.fetchall()
>>> rows
((1L, datetime.datetime(2014, 5, 21, 0, 0)), (1L, datetime.datetime(2014, 5, 22, 0, 0)) )
如何将返回的对象元组转换为字符串元组,如下所示:
(('1', '2014-05-21 00:00:00'), ('2', '2014-05-22 00:00:00'))
最佳答案
简单地迭代项目并将它们转换为元组,就像这样
print tuple(tuple(str(item) for item in items) for items in d)
# (('1', '2014-05-21 00:00:00'), ('1', '2014-05-22 00:00:00'))
这里我们使用了两个生成器表达式。最里面的一个 (str(item) for item in items
) 将对原始元组中的每个项目执行。当嵌套项被字符串化时,我们迭代生成器表达式并将其再次转换为元组。
关于python - 将对象元组转换为字符串元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23807328/