Trusted answers to developer questions

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.

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

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??? through utf-8 encoding.
  • 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 encode
string = 'pppfoo???'
#convert string to bytes
string_encode = string.encode('utf-8')
#ecode in base 64
encoded = base64.b64encode(string_encode)
#display encode data
print(encoded)
#decode from base 64
decoded = base64.b64decode(encoded)
#convert from bytes to string and display
print(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??? through utf-8 encoding.
  • The program then encodes the bytes in base64 and specifies in the altchars argument that / or + is encoded with :.
  • To check the correctness of the encoding, the program decodes the encoded data using the base64.b64decode() function. The altchars parameter 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 encode
string = 'pppfoo???'
#convert string to bytes
string_encode = string.encode('utf-8')
#ecode in base 64
encoded = base64.b64encode(string_encode, altchars=b'-:')
#display encode data
print(encoded)
#decode from base 64
decoded = base64.b64decode(encoded, altchars=b'-:')
#convert from bytes to string and display
print(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.

RELATED TAGS

python

CONTRIBUTOR

Ayesha Naeem
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?