![](/img/trans.png)
[英]TypeError: a bytes-like object is required, not 'str' but type is 'bytes'
[英]TypeError: a bytes-like object is required, not 'str' but type shows bytes
这段代码的output:
print(type(body))
body = body.replace('\n', '<br>')
产生:
<class 'bytes'>
TypeError: a bytes-like object is required, not 'str'
为什么当正文是字节 object 时会发生这种类型的错误?
我还按照这个问题的建议将replace()
arguments 测试为b'\n', b'<br>
,但没有运气。
TypeError: replace() argument 1 must be str, not bytes
这是完整的代码片段,作为参考,我试图在 web 页面上的 html 中显示 email 内容:
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)
改变这个
body = body.replace('\n', b'<br>')
对此
body = body.decode()
body = body.replace('\n', '<br>')
看起来替换方法在抱怨,因为它的字节像 object。 请发布body
内容,以便对其进行测试。
以下是示例案例:
>>> s = b'asdf\nasdfa\n'
>>> s
b'asdf\nasdfa\n'
>>> s.replace('\n','<br>')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
>>> s.decode().replace('\n','<br>')
'asdf<br>asdfa<br>'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.