How to base64 encode/decode a string in Python

Updated: June 1, 2023 By: Goodman Post a comment

This succinct, practical article shows you how to base64 encode/decode a string in Python.

Base64 encode a string

Base64 encoding is a process of converting a string into a format that uses a set of 64 characters to represent binary data, allowing safe transmission and storage of data that may contain special or non-printable characters.

In Python, you can use the b64encode() function from the base64 module to get the job done. Just follow the steps listed below:

  1. Import the base64 module.
  2. Encode the string to bytes using the appropriate encoding (e.g., UTF-8).
  3. Pass the encoded bytes to the base64.b64encode() function.
  4. Decode the resulting bytes object to a string using the appropriate decoding (e.g., UTF-8).

Code example:

import base64

string = "Welcome to Sling Academy!"

# Encode using base64.b64encode() function
encoded_string = base64.b64encode(string.encode("utf-8")).decode("utf-8")

print(encoded_string)

Output:

V2VsY29tZSB0byBTbGluZyBBY2FkZW15IQ==

Decode a base64 string to a human-readable string

Base64 decoding is the reverse process of base64 encoding. It involves converting a base64-encoded string back to its original form and recovering the original data from the encoded representation.

The way to decode a base64 string in Python is to use the b64decode() function from the base64 module. Below are the steps:

  1. Import the base64 module.
  2. Use the base64.b64decode() function to decode the string.
  3. Decode the result using the appropriate character encoding (mostly UTF-8).

Code example:

import base64

encoded_string = "V2VsY29tZSB0byBTbGluZyBBY2FkZW15IQ=="
decoded_bytes = base64.b64decode(encoded_string)
decoded_string = decoded_bytes.decode("utf-8")

print(decoded_string)

Output:

Welcome to Sling Academy!