Python Base64 Encode
To encode data in Base64, Python provides the b64encode
function of the base64
module. In addition, this module also provides the b64decode function, as well as other useful functions to encode binary into text using several algorithms specified in RFC 3548.
Usage:
b64encode(data)
- Encodesdata
to Base64 and returns value asstr
b64encode(data, altchars)
- Encodesdata
to Base64 and replaces+/
withaltchars
from the returnedstr
Arguments:
data
(required string) - Text or binary content that you want to encodealtchars
(optional string; defaultNone
) - Two characters that should replace “+” and “/”
Return Values:
str
- On success, it returns the Base64 value, typically longer by about 33% thandata
Supported Versions:
- Python 2.4+
Changelog:
-
Python 3.1:
- Adds the
encodebytes
function, which encodes bytes-like objects to Base64 - The function
encodestring
is deprecated
- Adds the
-
Python 3.4:
- Adds the
a85encode
function, which encodes data to Ascii85 - Adds the
b85encode
function, which encodes data to Base85 - Any bytes-like objects are now accepted by all encoding functions in the
base64
module
- Adds the
Example #1 (print the result):
from base64 import b64encode
data = 'guru'
print(b64encode(data)) #-> 'Z3VydQ=='
SyntaxError: bytes can only contain ASCII literal characters.
Example #2 (fix the “TypeError: a bytes-like object is required, not 'str'” error on Python 3):
from base64 import b64encode
data = b'guru'
print(b64encode(data)) #-> b'Z3VydQ=='
Example #3 (encode data into a custom Base64 alphabet):
from base64 import b64encode
data = '<<???>>'
print(b64encode(data)) #-> 'PDw/Pz8+Pg=='
print(b64encode(data, '-_')) #-> 'PDw_Pz8-Pg=='
Example #4 (fix the “SyntaxError: bytes can only contain ASCII literal characters” error on Python 3):
from base64 import b64encode
data = bytes('€100', 'utf-8')
print(b64encode(data)) #-> b'4oKsMTAw'
Example #5 (TypeError on missing required argument):
# Python 2.7 - b64encode() takes at least 1 argument (0 given)
# Python 3.6 - b64encode() missing 1 required positional argument: 's'
Example #6 (TypeError on wrong argument type):
# Python 2.7 - b2a_base64() argument 1 must be string or buffer, not int
# Python 3.6 - a bytes-like object is required, not 'int'
Comments (20)
I hope you enjoy this discussion. In any case, I ask you to join it.