1

我正在尝试解码 base 64 中的一些文本,但我不明白为什么在尝试这样做时会出错:

b'Zm9v'.decode('base64_codec')

引发的异常是:TypeError: expected bytes, not memoryview

base64PS:我知道有使用该模块的替代方案。但我有兴趣知道答案,只是出于好奇。

谢谢!

4

1 回答 1

3

不幸的是,bytes.decode()andstr.encode()方法(正确地)只支持也可以在类型之间转换的编解码器。bytes.decode()必须始终返回一个str对象,而str.encode()必须返回bytes;请参阅介绍这些编解码器的原始问题

编解码器可以使用任意类型,只是 unicode 和 bytes 对象上的辅助方法仅支持 Python 3.x 中的一种类型组合。

因此,您看到的具体错误是由于该bytes.decode()方法总是期望返回一个 type 的值str。同样,该str.encode()方法拒绝不bytes作为返回值返回的编解码器:

>>> 'Ceasar'.encode('rot_13')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: encoder did not return a bytes object (type=str)

因此,对于 bytes-to-bytes 和 str-to-str 编解码器,您需要codecs直接使用该模块:

import codecs

codecs.getdecoder('base64_codec')(b'Zm9v')[0]
于 2013-04-16T13:09:45.817 回答