TypeError:需要类似字节的对象,而不是'str',但类型显示字节

时间:2019-10-08 21:45:49

标签: python python-3.x string flask byte

此代码的输出:

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

以下是完整的代码段,以供参考,我试图在网页上以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)

1 个答案:

答案 0 :(得分:1)

更改此

body = body.replace('\n', b'<br>')

对此

body = body.decode()
body = body.replace('\n', '<br>')
  • 看起来替换方法在抱怨,因为它的字节像对象。请发布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>'