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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With