将对象元组转换为字符串元组

吉拉斯·贝哈迪(Ghilas BELHADJ)
>>> 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将对原始元组中的每个项目执行最里面的一个()。当嵌套的项目被字符串化时,我们迭代生成器表达式,然后再次将其转换为元组。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章