简体   繁体   中英

Base64 decoding

I'm trying to decode some text in base 64, and I don't understand why I get an error while trying to do that:

b'Zm9v'.decode('base64_codec')

The exception raised is: TypeError: expected bytes, not memoryview

PS: I know there's an alternative using the base64 module. But I'm interested in knowing the answer, just out of curiosity.

Thanks!

Unfortunately, the bytes.decode() and str.encode() methods (rightly) only support codecs that also convert between types; bytes.decode() must always return a str object, while str.encode() must return bytes ; see the original issue that introduced these codecs :

Codecs can work with arbitrary types, it's just that the helper methods on unicode and bytes objects only support one combination of types in Python 3.x.

So the specific error you see is caused by the fact that the bytes.decode() method always expects to return a value of type str . Similarly, the str.encode() method balks at codecs that do not return bytes as a return value:

>>> '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)

As such, for bytes-to-bytes and str-to-str codecs, you need to use the codecs module directly:

import codecs

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM