这是我的代码:


import imaplib
from email.parser import HeaderParser

conn = imaplib.IMAP4_SSL('imap.gmail.com')
conn.login('example@gmail.com', 'password')
conn.select()
conn.search(None, 'ALL')
data = conn.fetch('1', '(BODY[HEADER])')
header_data = data[1][0][1].decode('utf-8')

在这一点上,我得到错误消息:

AttributeError: 'str'对象没有'decode'属性

Python 3不再有str.decode(),所以我如何解决这个问题?


当前回答

我的情况可能有点罕见,但我正在使用django和我的项目在本地运行,但当我部署它时,似乎我得到了多个依赖错误,因为我正在做:pip冻结> requirements.txt这样做修复了这个问题:

pip3 freeze > requirements.txt

其他回答

在Python 3中,这个心智模型非常直接:

编码是将str对象转换为bytes对象的过程 解码是将bytes对象转换为str对象的过程

┏━━━━━━━┓                ┏━━━━━━━┓
┃       ┃ -> encoding -> ┃       ┃
┃  str  ┃                ┃ bytes ┃
┃       ┃ <- decoding <- ┃       ┃
┗━━━━━━━┛                ┗━━━━━━━┛

在你的例子中,你调用data.decode("UTF-8"),但是变量已经是一个str对象并且已经解码。所以只要直接引用数据,如果字符串是你需要的。

在使用Flask_JWT_extended包创建JWT access_token时,我得到了“str”对象没有属性“decode”。

为了解决这个问题,我升级了我的Flask-JWT-Extended包到Flask-JWT-Extended==4.1.0

供参考:

请访问此页面:https://flask-jwt-extended.readthedocs.io/en/stable/

如果你在PyJWT v2.0.0版本(22/12/2020)之后使用jwt身份验证登陆这里,你可能想要在requirements.txt文件中将你的PyJWT版本冻结到之前的版本。

PyJWT==1.7.1

这招对我很管用:

html.replace("\\/", "/").encode().decode('unicode_escape', 'surrogatepass')

这类似于json.loads(html)行为

使用codecs模块的open()读取文件:

import codecs
with codecs.open(file_name, 'r', encoding='utf-8', errors='ignore') as fdata: