Python base64 — Encode and Decode Bytes, URL-Safe Text, and Base85
Binary data has to travel through places built for text: a JSON field, a URL, an email body, a config value. Base64 is the standard way through — it rewrites any bytes as a short alphabet of letters, digits, and two extra characters, at the cost of a third more space. The base64 module does the whole job with no package to install, and it also carries the neighbouring encodings: a URL-safe alphabet, Base32, Base16, and the tighter Base85 family. This guide takes them in turn, then the validation switch and the errors a malformed string raises.
Written November 17, 2026 · Tested with Python 3.12.3 · 9 min read
- The main program: encode and decode
- The alphabets: standard, URL-safe, and custom
- Long output: line wrapping for email
- The wider family: Base32 and Base16
Written November 17, 2026
Tested with Python 3.12.3
What this guide is
The base64 module encodes binary data as printable text and decodes it back. Every function works on bytes: encoding takes bytes and returns bytes, and decoding takes the encoded bytes (or an ASCII string) and returns the original bytes. Nothing in the module reads files, talks to the network, or knows what the bytes mean — it is a pure change of representation, which is why the same two calls show up inside email, data URLs, basic authentication headers, and token formats.
The main program: encode and decode
b64encode reads three bytes at a time and writes four characters for each group, so the output is a third longer than the input. When the last group is short, the output is filled out with = padding characters. b64decode reverses the process exactly, and encoding empty bytes gives empty bytes back:
import base64
print(base64.b64encode(b"hello world"))
print(base64.b64encode(b"Veldica"))
print(base64.b64decode(b"aGVsbG8gd29ybGQ="))
print(base64.b64encode(b""))
print(base64.b64decode(base64.b64encode(b"any bytes \x00\x01")))
The exact output:
b'aGVsbG8gd29ybGQ='
b'VmVsZGljYQ=='
b'hello world'
b''
b'any bytes \x00\x01'
The padding count tells you how short the final group was: hello world is eleven bytes, so its last group holds two bytes and takes one =; Veldica is seven bytes, its last group holds one byte and takes two. Encoded text is still bytes, so turning it into a string for a JSON field or a header is one .decode("ascii") call, and the round trip on the last line shows the point of the exercise — bytes that no text format would carry, including a zero byte, survive unchanged.
The alphabets: standard, URL-safe, and custom
The standard alphabet ends with + and /, which are awkward in a URL, where a slash starts a new path segment. The URL-safe form swaps those two for - and _. Some byte values show the difference and most do not, because the two alphabets agree on every other character:
import base64
data = b"\xfb\xff\xfe"
print(base64.b64encode(data), base64.urlsafe_b64encode(data))
print(base64.b64encode(b"\xfa\xbc"))
print(base64.b64decode(b"+//+"), base64.urlsafe_b64decode(b"-__-"))
print(base64.b64encode(data, altchars=b"._"))
print(base64.b64decode(b".__.", altchars=b"._"))
The exact output:
b'+//+' b'-__-'
b'+rw='
b'\xfb\xff\xfe' b'\xfb\xff\xfe'
b'.__.'
b'\xfb\xff\xfe'
A program that puts encoded data in a URL or a filename uses the URL-safe pair of functions end to end. The third form, the altchars parameter, names any two replacement characters of your own, for a format that defines its own alphabet; it is a pair of characters, used for both encoding and decoding, and the two sides of a conversation have to agree on it, because nothing in the encoded text says which alphabet produced it.
Long output: line wrapping for email
Plain b64encode returns one unbroken line however long the input is. Email is the format that objects: the MIME rules wrap encoded data at 76 characters. encodebytes follows those rules — a newline after every 76 bytes of output, and a trailing newline at the end — and decodebytes reads that wrapped form back:
import base64
data = bytes(range(60))
print(len(base64.b64encode(data)))
print(base64.encodebytes(data))
print(base64.decodebytes(base64.encodebytes(data)) == data)
The exact output:
80
b'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4\nOTo7\n'
True
Sixty bytes encode to eighty characters, which is one full 76-character line, a short second line, and the two newlines. Outside email and the formats descended from it, the unwrapped form is the normal choice: a newline inside a JSON string or a header value is a problem of its own, and decoders that meet wrapped text in the wild are expected to skip the newlines, as the next sections show.
The wider family: Base32 and Base16
The same module carries two relatives that trade size for a smaller, safer alphabet. Base32 uses only the capital letters and the digits 2 to 7, encodes five bytes into eight characters, and suits places where case does not survive, such as a code a person reads aloud. Base16 is plain hexadecimal in upper case. Decoding is case-sensitive by default; casefold=True accepts lower case:
import base64, binascii
print(base64.b16encode(b"hello"), base64.b32encode(b"hello"))
print(base64.b32decode(b"NBSWY3DP"))
try:
base64.b32decode(b"nbswy3dp")
except binascii.Error as e:
print("binascii.Error:", e)
print(base64.b32decode(b"nbswy3dp", casefold=True))
print(base64.b16decode(b"68656C6C6F"), base64.b16decode(b"68656c6c6f", casefold=True))
The exact output:
b'68656C6C6F' b'NBSWY3DP'
b'hello'
binascii.Error: Non-base32 digit found
b'hello'
b'hello' b'hello'
The size ladder is the whole story here: Base16 doubles the data, Base32 grows it by three fifths, and Base64 by a third. A program picks the smallest alphabet its channel can carry intact — hex when the readers are people and debuggers, Base32 when case is unreliable, Base64 when the channel takes the full alphabet.
Tighter text: Base85 and Ascii85
Base85 packs four bytes into five characters, so the growth is a quarter instead of a third. The module has two variants: b85encode uses the alphabet defined by RFC 1924, the one Git uses, and a85encode uses the older Adobe variant from PostScript and PDF. They are not interchangeable — the same bytes encode to different text:
import base64
print(base64.b85encode(b"hello world"))
print(base64.a85encode(b"hello world"))
print(base64.b85decode(base64.b85encode(b"hello world")))
print(base64.a85encode(b"\x00\x00\x00\x00"))
print(base64.a85encode(b"hello world", adobe=True))
print(len(base64.b64encode(b"1234")), len(base64.b85encode(b"1234")))
The exact output:
b'Xk~0{Zy<MXa%^M'
b'BOu!rD]j7BEbo7'
b'hello world'
b'z'
b'<~BOu!rD]j7BEbo7~>'
8 5
The fourth line is an Ascii85 shortcut: a group of four zero bytes compresses to the single character z. The fifth line adds the Adobe framing, the <~ and ~> markers a PDF stream carries. The last line puts the saving in numbers: four bytes take eight characters in Base64, padding included, and five characters in Base85.
Validation: what a decoder ignores
Decoding is lenient by default. Characters outside the alphabet are thrown away before the padding is even checked, so line breaks, spaces, and stray marks in copied text do no harm — and also raise no warning. Passing validate=True turns that leniency off, and any character outside the alphabet is an error:
import base64, binascii
print(base64.b64decode(b"aGVs bG8=\n"))
print(base64.b64decode(b"aGVsbG8=$"))
try:
base64.b64decode(b"aGVs bG8=", validate=True)
except binascii.Error as e:
print("binascii.Error:", e)
The exact output:
b'hello'
b'hello'
binascii.Error: Only base64 data is allowed
The default is the right choice for text a person pasted, where a stray space is expected. Validation is the right choice for text a program produced and stored, where a stray character means the value was damaged or was never Base64 at all — the lenient decoder would quietly decode the undamaged prefix of it and hand back shorter bytes with no sign anything was lost.
The traps: text input, padding, and the wrong alphabet
TypeError — encode the string first. The padding is part of the data, so a string with its = signs stripped fails instead of decoding. And decoding returns bytes, never a string, so text has to be decoded from the result explicitly:import base64, binascii
try:
base64.b64encode("hello")
except TypeError as e:
print("TypeError:", e)
for bad in (b"aGVsbG8", b"a"):
try:
base64.b64decode(bad)
except binascii.Error as e:
print("binascii.Error:", e)
result = base64.b64decode("aGVsbG8=")
print(result, type(result).__name__)
try:
base64.b64decode("aGVsbG8=é")
except ValueError as e:
print("ValueError:", e)
print(base64.b64decode(b"-__-"))
The exact output:
TypeError: a bytes-like object is required, not 'str'
binascii.Error: Incorrect padding
binascii.Error: Invalid base64-encoded string: number of data characters (1) cannot be 1 more than a multiple of 4
b'hello' bytes
ValueError: string argument should contain only ASCII characters
b''
The last line is the quiet one. The standard decoder met URL-safe text, treated the - and _ characters as junk to discard, and decoded what was left — nothing — into empty bytes, with no error at all. A length that comes out wrong, or a payload that comes out empty, is often an alphabet mismatch rather than damaged data, and validate=True is how a program makes that mismatch loud instead of silent.
Which encoding for which job
| Job | Choice | Why |
|---|---|---|
| Bytes inside JSON, a header, or a config value | b64encode / b64decode |
The standard form every other tool reads |
| Encoded data in a URL or a filename | urlsafe_b64encode / urlsafe_b64decode |
No + or / to break the path |
| Encoded data in an email body | encodebytes |
Newlines every 76 characters, as MIME requires |
| A code people read, type, or say aloud | b32encode |
Letters and digits only, no case to lose |
| Data a person will inspect by eye | b16encode |
Plain hex, the form debuggers already show |
| The smallest text for a channel that allows it | b85encode |
Four bytes in five characters, a quarter of growth |
| Text from an untrusted or stored source | b64decode with validate=True |
Stray characters fail loudly instead of vanishing |
Checklist
- Encode bytes, not strings — call
.encode()on text first, and.decode("ascii")on encoded output that has to become a string. - Keep the padding: a stripped
=is damaged data, not a shorter spelling. - Match the alphabet on both sides; nothing in the text records which one wrote it.
- Use the URL-safe functions for anything that lands in a URL or a filename.
- Reach for
encodebytesonly where the MIME wrapping rules apply. - Decode stored or program-made values with
validate=True, so damage surfaces as an error. - Expect bytes back from every decode, and decode the text out of them yourself.
Related guides on this site
- Python hashlib — hash text, bytes, and files — the other standard bytes-to-text representation, one-way instead of reversible.
- Python JSON — dumps, loads, and files — the format whose string fields carry Base64 text so often.
- Python strings — slicing and methods — the text operations on either side of an encode or a decode.
Sources
- Python Standard Library,
base64—b64encodeandb64decode, the URL-safe andaltcharsalphabets,encodebytesand the 76-character MIME wrapping, the Base32 and Base16 functions andcasefold, the Base85 and Ascii85 variants, and thevalidateflag.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.