You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何去除SQLite3查询返回元组的括号与单引号?

解决SQLite查询结果显示带('和,)符号的问题

问题根源:cursor.fetchall()返回的是元组的列表,哪怕只查询了一列,每一行的结果也是一个单元素元组,直接打印元组就会出现('内容',)这类格式。

最优解决方案(循环适配任意条目数)

修改代码,遍历查询结果时取出元组的第一个元素,同时用循环自动生成序号:

def product_categories():
    product_categories_query = "SELECT Category_description \
                                FROM Categories \
                                ORDER BY Category_description"
    cursor.execute(product_categories_query)
    product_categories_rows = cursor.fetchall()

    # 遍历结果,从1开始生成序号
    for idx, row in enumerate(product_categories_rows, start=1):
        print(f"[{idx}] {row[0]}")

修改后输出效果:

[1] Audio and Hifi
[2] Cameras and accessories
[3] Computers and accessories
[4] Gaming
[5] Mobile phones and accessories
[6] TV and Home Cinema

硬编码写法(仅适配固定6条数据)

如果坚持保留原有的逐个打印方式,只需在每个结果后添加[0]取出元组内的文本:

print(f"[1] {product_categories_rows[0][0]}")
print(f"[2] {product_categories_rows[1][0]}")
print(f"[3] {product_categories_rows[2][0]}")
print(f"[4] {product_categories_rows[3][0]}")
print(f"[5] {product_categories_rows[4][0]}")
print(f"[6] {product_categories_rows[5][0]}")

内容的提问来源于stack exchange,提问作者Reina297

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 22:32:56