如何去除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
相关产品推荐
相关产品推荐

