2013-04-16 91 views
1

我想在基地64一些文本解码,我不明白为什么我得到一个错误,而试图做到这一点:Base64编码解码

b'Zm9v'.decode('base64_codec')

提出的例外是:TypeError: expected bytes, not memoryview

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

谢谢!

回答

4

不幸的是,bytes.decode()str.encode()方法(正确)只支持在类型之间进行转换的编解码器; bytes.decode()必须总是返回str对象,而str.encode()必须返回bytes;看到original issue that introduced these codecs

编解码器可任意类型的工作,它只是对Unicode的辅助方法和字节对象仅支持在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对海峡编解码器,则需要直接使用codecs模块:

import codecs 

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

感谢您的回答! –