1. 程式人生 > 實用技巧 >decoding to str: need a bytes-like object, tuple found

decoding to str: need a bytes-like object, tuple found

一、

在訪問python-web專案的某網頁時,顯示decoding to str: need a bytes-like object, tuple found錯誤。

二、

錯誤大概意思是解碼成字串是需要位元組類的物件,但現在發現了一個元組型別物件。
找到後臺程式碼:

db=pymysql.connect(host='localhost',port=3306,user='root',password='123456',database='stock_db',charset='utf8')
cursor=db.cursor()
sql="select * from info;"
cursor.execute(sql)
data_from_mysql
=cursor.fetchall() cursor.close() db.close() content=re.sub(r"\{%content%\}", data_from_mysql, content) return content

發現

data_from_mysql=cursor.fetchall()

返回的是是多行記錄,是一個二維元組。類似於((username1,password1,nickname1),(username2,password2,nickname2),(username3,password3,nickname))
而在

content=re.sub(r"\{%content%\}
", data_from_mysql, content)

中直接將data_from_mysql當做字串來處理~

解決:

content=re.sub(r"\{%content%\}", data_from_mysql, content)

改成

content=re.sub(r"\{%content%\}", str(data_from_mysql), content)

,也就是使用str來轉化data_from_mysql的型別。



Accept what was and what is, and you’ll have more positive energy to pursue what will be.