For Base64 encoding, do you prefer str.encode ('base64_codec') or base64.b64encode (str)?

The Python library has a base64 module for working with Base64. At the same time, if you want to encode a string, there is a codec for base64, i.e. str.encode('base64_encode') . Which approach is preferable?

+4
source share
2 answers

Although this may work for Python 2:

 >>> 'foo'.encode('base64') 'Zm9v\n' 

Python 3 does not support it:

 >>> 'foo'.encode('base64') Traceback (most recent call last): File "<stdin>", line 1, in <module> LookupError: unknown encoding: base64 

And in terms of speed (in Python 2), the b64encode method b64encode about three times faster than .encode() :

 In [1]: %timeit 'fooasodaspf8ds09f8'.encode('base64') 1000000 loops, best of 3: 1.62 us per loop In [5]: %timeit b64encode('fooasodaspf8ds09f8') 1000000 loops, best of 3: 564 ns per loop 

So, in terms of speed and compatibility, the base64 module is better.

+9
source

Just for reference, there is another option that works in both Python 2.4+ and 3.2+:

 >>> from codecs import encode >>> encode(b'fooasodaspf8ds09f8', 'base64') b'Zm9v\n' 

It also allows you to encode / decode gzip and bzip2 among other things.

https://docs.python.org/3.4/library/codecs.html#binary-transforms

http://wingware.com/psupport/python-manual/3.4/whatsnew/3.4.html#improvements-to-codec-handling

0
source

All Articles