Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

codec

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?

like image 456
Raymond Tau Avatar asked Dec 27 '22 05:12

Raymond Tau


1 Answers

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.

like image 170
Blender Avatar answered Dec 29 '22 00:12

Blender