base64 | Python Standard Library – Real Python
The Python base64 module provides functions for encoding binary data as printable ASCII characters and decoding those representations back to binary.
It implements the Base16, Base32, and Base64 encodings defined in RFC 4648, as well as the non-standard Base85 encoding. It’s useful when binary data must pass through text-based protocols, such as email, URLs, or HTTP.
Here’s a quick example:
Key Features
- Encodes and decodes Base64, Base32, Base16, and Base85 data
- Provides URL-safe Base64 variants that replace
+with-and/with_ - Supports MIME-compliant encoding with newlines every 76 characters via
encodebytes() - Accepts bytes-like objects and ASCII strings as inputs to decoding functions
Frequently Used Functions
Examples
Encoding and decoding with the standard Base64 alphabet:
Comparing the standard and URL-safe alphabets on bytes that produce + and /:
Common Use Cases
The most common tasks for base64 include:
- Encoding binary files (images, PDFs) for embedding in JSON, XML, or HTML data URIs
- Generating URL-safe tokens for password resets and API keys
- Encoding email attachments in MIME format
- Transmitting binary data over text-only channels or protocols
Real-World Example
Consider embedding a PNG image, logo.png, as a data URI for use directly in an HTML page:
When you run this script, you get an output like the following:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAA...
The .b64encode() call converts the raw bytes to a string the browser can read inline, eliminating the need for a separate image request.
Tutorial
Bytes Objects: Handling Binary Data in Python
In this tutorial, you'll learn about Python's bytes objects, which help you process low-level binary data. You'll explore how to create and manipulate byte sequences in Python and how to convert between bytes and strings. Additionally, you'll practice this knowledge by coding a few fun examples.
For additional information on related topics, take a look at the following resources:
- How to Convert Bytes to Strings in Python (Tutorial)
- Python's Bytearray: A Mutable Sequence of Bytes (Tutorial)
- Sending Emails With Python (Tutorial)
- Python Bytes (Quiz)
- How to Convert Bytes to Strings in Python (Quiz)
- Python's Bytearray (Quiz)
- Sending Emails Using Python (Course)