How to use base64.b64encode() in Python
The base64.b64() function in Python encodes byte-like objects and returns the encoded bytes.
Prototype and parameters
The base64.b64encode() function takes s as a non-optional parameter and altchars as an optional parameter.
scontains a byte-like object that is to be encoded.altcharsspecifies alternative characters for encoded+or/characters.altcharsis a byte-like object and must have a minimum length of 2.
The
altcharsparameter enables URL and filesystem safe base64 encoding.
Examples
Example 1
The following code demonstrates how to encode binary data in base64 without alternative characters:
- The program obtains the binary form of the string
pppfoo???throughutf-8encoding. - The program then encodes the bytes in base64 and displays the encoded data.
- To check the correctness of the encoding, the program decodes the encoded data using the
base64.b64decode()function. - The decoded form is converted from binary to strings and displayed. The initial and final strings are identical, as illustrated.
import base64#string to encodestring = 'pppfoo???'#convert string to bytesstring_encode = string.encode('utf-8')#ecode in base 64encoded = base64.b64encode(string_encode)#display encode dataprint(encoded)#decode from base 64decoded = base64.b64decode(encoded)#convert from bytes to string and displayprint(decoded.decode('utf-8'))
Example 2
The following program demonstrates how to encode a byte-like object in base64 with alternative characters.
- The program obtains the binary form of the string
pppfoo???throughutf-8encoding. - The program then encodes the bytes in base64 and specifies in the
altcharsargument that/or+is encoded with:. - To check the correctness of the encoding, the program decodes the encoded data using the
base64.b64decode()function. Thealtcharsparameter is input to ensure correct decoding of:. - The decoded form is converted from binary to strings and displayed. The initial and final strings are identical, as illustrated.
import base64#string to encodestring = 'pppfoo???'#convert string to bytesstring_encode = string.encode('utf-8')#ecode in base 64encoded = base64.b64encode(string_encode, altchars=b'-:')#display encode dataprint(encoded)#decode from base 64decoded = base64.b64decode(encoded, altchars=b'-:')#convert from bytes to string and displayprint(decoded.decode('utf-8'))
Note that both the examples use the same initial string, but the encoded data in example 1 contains
/as the last character, and the encoded data in example 2 contains:as the last character.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved