Base64 Encoding in Python — Complete Guide with Examples

Python's standard library ships a built-in base64 module, so you never need a third-party package to encode or decode Base64. The tricky part isn't the API — it's remembering that Python's Base64 functions work on bytes, not str. This guide walks through encoding strings, files, and URL-safe variants with working code.

Encoding a string to Base64

You first need to convert your string to bytes using .encode(), then pass those bytes to base64.b64encode(). The result is also bytes, so decode it back to a string with UTF-8 if you want to print or store it as text.

import base64

text = "Hello, World!"
text_bytes = text.encode("utf-8")

encoded_bytes = base64.b64encode(text_bytes)
encoded_str = encoded_bytes.decode("utf-8")

print(encoded_str)
# → SGVsbG8sIFdvcmxkIQ==

Decoding Base64 back to a string

import base64

encoded_str = "SGVsbG8sIFdvcmxkIQ=="

decoded_bytes = base64.b64decode(encoded_str)
decoded_str = decoded_bytes.decode("utf-8")

print(decoded_str)
# → Hello, World!

Encoding files and binary data

Open the file in binary mode ("rb") so Python reads raw bytes instead of trying to decode it as text. This is the same technique used to embed images in JSON payloads or send attachments over APIs that only accept text fields.

import base64

with open("photo.png", "rb") as f:
    file_bytes = f.read()

encoded = base64.b64encode(file_bytes).decode("utf-8")

# Write it back out to a new file to verify round-trip
with open("photo_copy.png", "wb") as f:
    f.write(base64.b64decode(encoded))

URL-safe Base64 in Python

Standard Base64 output can contain + and /, which have special meaning in URLs and file paths. Python's urlsafe_b64encode swaps them for - and _ so the output can be used directly in a URL path, query string, or filename — this is exactly what's used inside JWTs.

import base64

data = b'{"user_id": 42, "role": "admin"}'

url_safe = base64.urlsafe_b64encode(data).decode("utf-8")
print(url_safe)
# → eyJ1c2VyX2lkIjogNDIsICJyb2xlIjogImFkbWluIn0=

# Decoding is symmetric
original = base64.urlsafe_b64decode(url_safe)
print(original.decode("utf-8"))

Common errors and how to fix them

  • binascii.Error: Incorrect padding — Base64 strings must be a multiple of 4 characters. Pad manually with input + '=' * (-len(input) % 4) before decoding if the source stripped padding.
  • AttributeError: 'str' object has no attribute 'decode' — you passed a string directly to b64encode. Call .encode("utf-8") first to get bytes.
  • UnicodeDecodeError on b64decode result — the decoded bytes aren't valid UTF-8 text (e.g. it's actually an image). Only call .decode("utf-8") when you know the original data was text.
  • Mixing standard and URL-safe alphabets — decoding a URL-safe string with b64decode (instead of urlsafe_b64decode) fails or silently produces wrong bytes because -/_ aren't in the standard alphabet.

Quick reference: base64 module functions

base64.b64encode(bytes)          # standard Base64 encode
base64.b64decode(bytes_or_str)   # standard Base64 decode
base64.urlsafe_b64encode(bytes)  # URL-safe encode (-, _ instead of +, /)
base64.urlsafe_b64decode(bytes)  # URL-safe decode
base64.b32encode(bytes)          # Base32 encode (different alphabet)
base64.b16encode(bytes)          # Base16 / hex encode

Frequently Asked Questions

How do you Base64 encode a string in Python?

Import the base64 module, encode your string to bytes, then call base64.b64encode(). For example: base64.b64encode("hello".encode("utf-8")).decode("utf-8") returns the Base64 string.

Why does base64.b64encode() return bytes instead of a string?

Python's base64 module works on bytes objects, not strings, because Base64 is fundamentally a binary-to-text encoding. Call .decode("utf-8") on the result to convert the output bytes into a regular Python string.

What is the difference between b64encode and urlsafe_b64encode in Python?

b64encode uses the standard Base64 alphabet, which includes + and / characters. urlsafe_b64encode replaces + with - and / with _, making the output safe to use directly inside URLs and filenames without additional encoding.

Try the Free Base64 Encoder/Decoder

Skip the boilerplate — paste any string or Base64 value into our free online tool to encode or decode instantly, right in your browser. No installs, no data uploaded.

Related articles