【问题标题】:TypeError: a bytes-like object is required, not 'str' but type shows bytesTypeError:需要一个类似字节的对象,而不是“str”,但类型显示字节
【发布时间】: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'&lt;br&gt; 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'&lt;br&gt;')而不是body.replace('\n', '&lt;br&gt;')
  • @juanpa.arrivillaga OP 试过了,但它不起作用。在帖子中提到。

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


【解决方案1】:

改变这个

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

到这里

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

【讨论】:

  • print(body) 语句显示由于某种原因有一个语句是&lt;class 'str'&gt;。我添加了一个 if 语句来检查类型:if type(body) == bytes:body = body.decode()
猜你喜欢
  • 2019-11-27
  • 2016-01-05
相关资源
最近更新 更多