Base64 Encode & Decode in Python

Encode or decode below — it runs locally in your browser — then grab the canonical Python code. Python's standard-library base64 module works with bytes, so you .encode() a string before encoding and .decode() the result after.

INPUT
OUTPUT
Type or paste to encode / decode

Encode and decode a string

The key pattern is str → .encode() → b64encode() → .decode() → str:

import base64

# Encode
encoded = base64.b64encode("Hello, world!".encode("utf-8")).decode("ascii")
print(encoded)  # SGVsbG8sIHdvcmxkIQ==

# Decode
decoded = base64.b64decode("SGVsbG8sIHdvcmxkIQ==").decode("utf-8")
print(decoded)  # Hello, world!

Tip: b64encode needs bytes. Passing a str raises TypeError: a bytes-like object is required — always .encode() first.

URL-safe Base64

For JWTs, URLs, and filenames, use the URL-safe alphabet (- and _ instead of + and /):

import base64

# URL-safe encode, padding stripped (JWT-style)
def b64url_encode(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")

# URL-safe decode, restoring padding
def b64url_decode(s: str) -> bytes:
    s += "=" * (-len(s) % 4)
    return base64.urlsafe_b64decode(s)

Encode a file

import base64

with open("image.png", "rb") as f:
    encoded = base64.b64encode(f.read()).decode("ascii")

# As a data URI for HTML/CSS:
data_uri = "data:image/png;base64," + encoded

Frequently asked questions

How do I Base64 encode a string in Python?

Encode the string to bytes, then Base64-encode: base64.b64encode("Hello".encode("utf-8")).decode("ascii") returns "SGVsbG8=".

How do I Base64 decode in Python?

base64.b64decode("SGVsbG8=") returns b"Hello"; add .decode("utf-8") for a string.

How do I do URL-safe Base64?

Use base64.urlsafe_b64encode() / urlsafe_b64decode(), and .rstrip(b"=") to drop padding.

Why does b64encode raise a TypeError?

It needs bytes, not str. Call .encode("utf-8") on the string first.

Need image, file, or URL-safe modes?

The main base64.dev tool handles text, images, files, and URL-safe Base64 with auto-detect.

Open base64.dev →