Base64 in Python

Last updated: February 2026

How to encode and decode Base64 strings in Python using the base64 module

How Do You Encode a String to Base64 in Python?

Use base64.b64encode() from the standard library. This function accepts a bytes object and returns a bytes object containing the Base64-encoded ASCII characters. Convert the input string to bytes with .encode('utf-8') first, then call .decode('ascii') on the result to get a regular Python string.

import base64

original = "Hello, World!"
encoded = base64.b64encode(original.encode("utf-8"))
print(encoded)           # b'SGVsbG8sIFdvcmxkIQ=='
print(encoded.decode("ascii"))  # SGVsbG8sIFdvcmxkIQ==

The b64encode() function uses the standard Base64 alphabet (A-Z, a-z, 0-9, +, /) with = padding as defined in RFC 4648 Section 4. The module is included in every Python installation, so no pip install is required. To encode text without writing code, use the Base64 text encoder. For an overview of the encoding format, see What is Base64?.

How Do You Decode Base64 in Python?

Use base64.b64decode() to convert a Base64 string back to its original bytes. The function accepts a bytes object or an ASCII str and returns the decoded bytes. Call .decode('utf-8') on the result to reconstruct the original string. Invalid input raises binascii.Error.

import base64

decoded = base64.b64decode("SGVsbG8sIFdvcmxkIQ==")
print(decoded)                # b'Hello, World!'
print(decoded.decode("utf-8"))  # Hello, World!

The validate parameter (Python 3.x) controls strictness. Setting validate=True raises an exception if the input contains characters outside the Base64 alphabet. By default, non-Base64 characters are silently discarded. To decode Base64 interactively in your browser, use the Base64 text decoder.

How Do You Encode a File to Base64 in Python?

Open the file in binary read mode ('rb'), read its contents, and pass the bytes to base64.b64encode(). This loads the entire file into memory. For images, prepend the MIME type to create a data URI suitable for embedding in HTML or CSS.

import base64

# Encode a file to Base64
with open("image.png", "rb") as f:
    file_bytes = f.read()
    encoded = base64.b64encode(file_bytes).decode("ascii")

# Create a data URI
data_uri = f"data:image/png;base64,{encoded}"
print(data_uri[:50])  # data:image/png;base64,iVBORw0KGgo...

For large files, consider reading and encoding in chunks using base64.encodebytes() or processing with streaming I/O. The Base64 file encoder performs the same operation directly in your browser without uploading the file to any server.

How Do You Use URL-Safe Base64 in Python?

Use base64.urlsafe_b64encode() and base64.urlsafe_b64decode() for URL-safe output. These functions replace + with - and / with _ as defined in RFC 4648 Section 5. The padding character = is still included by default; strip it manually if needed.

import base64

data = b"subjects?abcd"

# URL-safe encoding
encoded = base64.urlsafe_b64encode(data)
print(encoded)  # b'c3ViamVjdHM_YWJjZA=='

# URL-safe decoding
decoded = base64.urlsafe_b64decode(encoded)
print(decoded)  # b'subjects?abcd'

# Remove padding for JWT-style tokens
no_pad = encoded.rstrip(b"=")
print(no_pad)   # b'c3ViamVjdHM_YWJjZA'

URL-safe encoding prevents conflicts when Base64 strings appear in query parameters, file names, or URL path segments. The URL-safe Base64 tool provides browser-based encoding with the same alphabet. For details on Base64 special characters and how they map to indices, see the Base64 character table.

What Python Base64 Functions Are Available?

The base64 module provides encoding and decoding functions for Base64, Base32, and Base16 alphabets. The table below lists every public function, its input type, output format, and primary use case.

FunctionInputOutputDescription
b64encode(s)bytesbytesStandard Base64 encoding (RFC 4648 §4)
b64decode(s)bytes or strbytesStandard Base64 decoding
urlsafe_b64encode(s)bytesbytesURL-safe encoding (RFC 4648 §5)
urlsafe_b64decode(s)bytes or strbytesURL-safe decoding
b32encode(s)bytesbytesBase32 encoding (RFC 4648 §6)
b32decode(s)bytes or strbytesBase32 decoding
b16encode(s)bytesbytesBase16 (hex) encoding
b16decode(s)bytes or strbytesBase16 (hex) decoding
encodebytes(s)bytesbytesMIME-style encoding with newlines every 76 chars
decodebytes(s)bytesbytesDecode MIME-style Base64 with line breaks

All functions operate on bytes objects. Convert strings to bytes with .encode('utf-8') before encoding. The b16encode output is equivalent to hexadecimal; for hex-to-Base64 conversion, see the Base64 hex converter.

How Does Python Base64 Handle Unicode?

Python 3 strictly separates str (Unicode text) from bytes (raw data). The b64encode() function requires a bytes input. Passing a str directly raises TypeError. Always call .encode('utf-8') on the string first to produce the UTF-8 byte representation.

import base64

# Unicode string with emoji
text = "Hello 🌍"

# Step 1: Convert str to bytes (UTF-8 encoding)
text_bytes = text.encode("utf-8")
print(text_bytes)  # b'Hello \xf0\x9f\x8c\x8d'

# Step 2: Base64 encode the bytes
encoded = base64.b64encode(text_bytes)
print(encoded)     # b'SGVsbG8g8J+MjQ=='

# Step 3: Decode back
decoded_bytes = base64.b64decode(encoded)
result = decoded_bytes.decode("utf-8")
print(result)      # Hello 🌍

The key sequence is: str.encode('utf-8')bytesb64encode() → Base64 bytes. Reversing the process: Base64 bytesb64decode()bytes.decode('utf-8')str. This pattern works for any Unicode text, including emoji, CJK characters, and right-to-left scripts.

Frequently Asked Questions

What is the Python module for Base64 encoding?

Python's standard library includes the base64 module. Import it with import base64. The module provides functions for encoding and decoding data using Base64, Base32, Base16, and Ascii85 alphabets as defined in RFC 4648 and RFC 3548. No pip install or third-party package is needed.

Does Python Base64 support URL-safe encoding?

Yes. The base64 module provides urlsafe_b64encode() and urlsafe_b64decode() functions. These use the URL-safe alphabet defined in RFC 4648 Section 5, replacing + with - and / with _ in the output. The padding character = is still included by default.

How do you encode an image to Base64 in Python?

Open the image file in binary mode with open('image.png', 'rb'), read its contents with .read(), then pass the bytes to base64.b64encode(). The result is a bytes object containing the Base64 string. Call .decode('ascii') to convert it to a regular Python string for use in HTML data URIs or JSON.

What is the difference between encodebytes and b64encode in Python?

b64encode() returns a single continuous Base64 string with no line breaks. encodebytes() inserts a newline character every 76 bytes and adds a trailing newline, following the MIME format (RFC 2045). Use b64encode() for data URIs, APIs, and JSON. Use encodebytes() only when MIME-formatted output with line breaks is specifically required.

Do you need to pip install base64 in Python?

No. The base64 module is part of Python's standard library and is included with every Python installation (Python 2 and Python 3). You do not need to run pip install or add any dependency. Simply write import base64 at the top of your script to start using it.

Related Base64 Tools and Guides