Base64解码

时间:2013-04-16 12:56:39

标签: python python-3.x base64 byte codec

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

b'Zm9v'.decode('base64_codec')

引发的例外是:TypeError: expected bytes, not memoryview

PS:我知道有一个使用base64模块的替代方案。但出于好奇,我有兴趣知道答案。

谢谢!

1 个答案:

答案 0 :(得分:3)

不幸的是,bytes.decode()str.encode()方法(正确地)仅支持也在类型之间转换的编解码器; bytes.decode()必须始终返回str个对象,而str.encode()必须返回bytes;请参阅original issue that introduced these codecs

  

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

因此,您看到的具体错误是由bytes.decode()方法总是希望返回类型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)

因此,对于字节到字节和str到str的编解码器,您需要直接使用codecs模块:

import codecs

codecs.getdecoder('base64_codec')(b'Zm9v')[0]