Python 3.10列表推导式调用str.strip()等字符串方法意外报错求解
报错'list' object has no attribute 'strip'和Python 3.x版本语法无关,是你遍历的对象层级错误导致的。
问题根源说明
cur.fetchall()返回的是元组嵌套结构,每一行查询结果是一个内层元组。你执行result = [list(item) for item in result]之后,result变成了二维列表结构,每个元素是对应行的列表,不是字符串,直接对列表调用字符串专属的strip方法自然会报错。- 你之前同类操作成功的场景,应该是直接遍历一维字符串序列,没有嵌套列表的中间层。
- 补充:你代码里的
strip方法传参也不符合规范,str.strip()仅接收1个参数(要移除的首尾字符集合),你写的strip("'", "")属于非法传参,后续也要修正。
修正代码
根据常用场景选择对应方案即可:
场景1:保留查询结果的行结构,每行的所有元素去除首尾单引号
try: result = cur.fetchall() # result = (1, 2, 3,) or result = ((1, 3), (4, 5),) final_result = [] for row in result: # 先转字符串再去引号,兼容数值类型的查询结果 processed_row = [str(item).strip("'") for item in row] final_result.append(processed_row) except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() return final_result
场景2:不需要保留行结构,直接把所有查询结果扁平化处理为一维列表
try: result = cur.fetchall() # result = (1, 2, 3,) or result = ((1, 3), (4, 5),) final_result = [str(item).strip("'") for row in result for item in row] except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() return final_result
内容的提问来源于stack exchange,提问作者Max Dylan
相关产品推荐
相关产品推荐

