A virtual teacher who reveals to you the great secrets of Base64

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) - Encodes data to Base64 and returns value as str
  • b64encode(data, altchars) - Encodes data to Base64 and replaces +/ with altchars from the returned str

Arguments:

  • data (required string) - Text or binary content that you want to encode
  • altchars (optional string; default None) - Two characters that should replace “+” and “/”

Return Values:

  • str - On success, it returns the Base64 value, typically longer by about 33% than data

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
  • 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

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'
Add new comment

If you have any questions, remarks, need help, or just like this page, please feel free to let me know by leaving a comment using the form bellow.
I will be happy to read every comment and, if necessary, I will do my best to respond as quickly as possible. Of course, spammers are welcome only as readers.

Loading...