2013-04-16 187 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

感謝您的回答! –