首页 > 解决方案 > 如何在 Python 中删除变量中不必要的字符

问题描述

如何从中删除多余的括号result{{ }}

连接数据库的代码:

import pymysql

try:
    db = pymysql.connect(host='localhost', user='root', password='', db='testdb', )
    cursor = db.cursor()
    cursor.execute("SELECT text FROM wiadomosci WHERE msgid=1")
    result = cursor.fetchall()
except:
    result = '[Something went wrong][1] :('

tkinter 的代码:

textExample = Text(window, height=1)
textExample.insert(1.0, "Message from owner: ")
textExample.config(state=DISABLED)
textExample.pack()

textExample2 = Text(window, height=3)
textExample2.insert(1.0, result)
textExample2.config(state=DISABLED)
textExample2.pack()

问题照片

标签: pythonmysqltkinter

解决方案


您正在将列表或元组传递给需要字符串的方法。在您的情况下,result是表示行和列的元组的元组。当你这样做时,tkinter 会根据底层 tcl 解释器处理列表的方式添加花括号。

解决方案是将您的数据显式转换为字符串,而不是让 tcl 执行此操作,或者从数据中提取字符串。

例如,如果你想要第一行的第一列,result你可以这样做:

textExample2.insert("1.0", result[0][0])

您也可以使用fetchone它只返回一行。您仍然必须从第一列中提取数据。这设置result为第一列中的字符串:

result = cursor.fetchone()[0]

推荐阅读