【发布时间】:2020-02-06 05:16:55
【问题描述】:
这段代码的输出:
print(type(body))
body = body.replace('\n', '<br>')
产生:
<class 'bytes'>
TypeError: a bytes-like object is required, not 'str'
为什么body是字节对象时会出现这种类型的错误?
我还测试了replace() 参数为b'\n', b'<br> as suggested in this question,但没有运气。
TypeError: replace() argument 1 must be str, not bytes
这是完整的代码 sn-p,作为参考,我正在尝试在网页上以 html 格式显示电子邮件内容:
def GetMimeMessage(service, user_id, msg_id):
try:
message = service.users().messages().get(userId=user_id, id=msg_id, format='raw').execute()
msg_bytes = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
b = email.message_from_bytes(msg_bytes)
body = ""
if b.is_multipart():
for part in b.walk():
ctype = part.get_content_type()
cdispo = str(part.get('Content-Disposition'))
# skip any text/plain (txt) attachments
if ctype == 'text/plain' and 'attachment' not in cdispo:
body = part.get_payload(decode=True) # decode
break
# not multipart - i.e. plain text, no attachments, keeping fingers crossed
else:
body = b.get_payload(decode=True)
print(type(body))
body = body.replace('\n', b'<br>')
return body
except errors.HttpError as error:
print ('An error occurred: %s' % error)
【问题讨论】:
-
你能做到
print(body)并发布出现的情况吗? -
您的 参数 也必须是
bytes对象。所以你使用body.replace(b'\n', b'<br>')而不是body.replace('\n', '<br>') -
@juanpa.arrivillaga OP 试过了,但它不起作用。在帖子中提到。
标签: python python-3.x string flask byte