The base64.b64()
function in Python encodes byte-like objects and returns the encoded bytes.
The base64.b64encode()
function takes s
as a non-optional parameter and altchars
as an optional parameter.
s
contains a byte-like object that is to be encoded.altchars
specifies alternative characters for encoded +
or /
characters. altchars
is a byte-like object and must have a minimum length of 2.The
altchars
parameter enables URL and filesystem safe base64 encoding.
The following code demonstrates how to encode binary data in base64
without alternative characters:
pppfoo???
through utf-8
encoding.base64.b64decode()
function.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'))
The following program demonstrates how to encode a byte-like object in base64 with alternative characters.
pppfoo???
through utf-8
encoding.altchars
argument that /
or +
is encoded with :
.base64.b64decode()
function. The altchars
parameter is input to ensure correct decoding of :
.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