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

标签 python tuples

>>> 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/

相关文章:

error-handling - ML。 “Unzipping”元组列表。

python - 安装 python 轮文件, '*.whl"结果为 "... is not a supported wheel on this platform"

python - 元组错误中的元组

Python - 将元组列表水平写入文本文件

python - 在 matplotlib 中设置颜色条范围

scala - 为什么以及如何在调用单参数函数时特别处理元组?

c# - 我可以使用 Linq 从 IEnumerables 构建元组吗?

python 猜谜游戏练习

python - RGB 图像的像素强度以及如何将其与整数相乘以查看灰色阴影

python - 处理模块名称冲突