Raymond Tau
Raymond Tau

Reputation: 3479

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

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

Upvotes: 4

Views: 3215

Answers (2)

Stefan Friesel
Stefan Friesel

Reputation: 823

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

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

This also enables encoding/decoding 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

Upvotes: 1

Blender
Blender

Reputation: 298354

While it may work for Python 2:

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

Python 3 doesn't 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 is 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 both speed and compatibility, the base64 module is better.

Upvotes: 9

Related Questions