Base64 decode in Python.
Python's standard library decodes Base64 with one call. The trouble starts with the details: it returns bytes, it is strict about padding, and it quietly drops URL-safe characters. This guide covers each of those with code you can paste.
Updated 9 November 2026
Use base64.b64decode(s). It returns bytes; call .decode("utf-8") on the result if you expect text. For URL-safe strings (with - and _, as in JWTs) use base64.urlsafe_b64decode(s). If you get binascii.Error: Incorrect padding, add the missing = with s + "=" * (-len(s) % 4).
The basic decode
The base64 module ships with Python, so there is nothing to install.
import base64
data = base64.b64decode("SGVsbG8sIHdvcmxkIQ==")
print(data) # b'Hello, world!'
print(data.decode("utf-8")) # Hello, world!
b64decode accepts a str or bytes and always returns bytes. That is deliberate: Base64 can carry anything (an image, a zip file, a key), and only you know whether the bytes are text. If they are, decode them with the character set they were written in. For almost all modern data that is UTF-8.
Standard vs URL-safe Base64
There are two Base64 alphabets in RFC 4648. They differ only in two characters:
| Alphabet | Characters 62 and 63 | Python function | Where you see it |
|---|---|---|---|
| Standard (§4) | + / | base64.b64decode | Email attachments, data URIs, PEM files, most APIs |
| URL-safe (§5) | - _ | base64.urlsafe_b64decode | JWTs, OAuth tokens, URLs, file names |
Using the wrong function is the most common Python Base64 bug, because by default b64decode does not raise an error on - or _. It silently throws them away and decodes what is left, which gives you wrong bytes or a confusing padding error:
import base64
base64.urlsafe_b64decode("_-7d") # b'\xff\xee\xdd' (correct)
base64.b64decode("_-7d") # binascii.Error: Incorrect padding
# ("_" and "-" were dropped, leaving "7d")
If you don't know which alphabet a string uses, normalise it first. Converting - to + and _ to / is safe, because a standard string never contains - or _:
def b64decode_any(s: str) -> bytes:
s = s.strip().replace("-", "+").replace("_", "/")
return base64.b64decode(s + "=" * (-len(s) % 4))
To catch bad input instead of skipping it, pass validate=True. Then anything outside the standard alphabet raises binascii.Error. (Whitespace and newlines are accepted when validate is off, which is what you want for wrapped MIME or PEM data.)
Fixing "Incorrect padding"
Base64 output is always a multiple of 4 characters long, padded with = at the end. Many systems drop the padding, including JWTs and most URL-safe tokens. Python refuses to guess, so an unpadded string raises an error:
>>> base64.b64decode("SGVsbG8")
binascii.Error: Incorrect padding
Add back as many = as needed to reach a multiple of 4. -len(s) % 4 gives exactly that number (0, 1 or 2 for valid input):
def pad(s: str) -> str:
return s + "=" * (-len(s) % 4)
base64.b64decode(pad("SGVsbG8")) # b'Hello'
Adding extra padding is harmless: b64decode("SGVsbG8===") also works, which is why some code just appends "==". The modulo version is clearer about intent.
If padding doesn't fix it, the string itself is damaged. Python 3.13 says so directly: Invalid base64-encoded string: number of data characters (1) cannot be 1 more than a multiple of 4. That length can't come from any encoder, so the string was probably cut off when it was copied. Our padding guide explains the arithmetic.
bytes to text, and UnicodeDecodeError
If .decode("utf-8") fails with UnicodeDecodeError, the Base64 was fine but the bytes inside are not UTF-8 text. There are three usual reasons:
- It isn't text. An image or PDF will never decode as UTF-8. Write it to a file instead (see below).
- It's text in another encoding. Try
.decode("latin-1"),"cp1252"or"utf-16". (PowerShell's-EncodedCommandis UTF-16LE, for example.) - It's compressed. If the Base64 starts with
H4sI, the bytes are gzip. Run them throughgzip.decompress()first.
import base64, gzip
raw = base64.b64decode(s)
if raw[:2] == b"\x1f\x8b": # gzip magic bytes
raw = gzip.decompress(raw)
text = raw.decode("utf-8", errors="replace") # never raises; bad bytes become �
Decode Base64 to a file
For anything binary, write the bytes straight to disk with "wb" mode. Don't call .decode() at all:
import base64
with open("output.pdf", "wb") as f:
f.write(base64.b64decode(b64_string))
If the string came from a web page or an API, it may start with a data URI prefix such as data:application/pdf;base64,. Remove everything up to the first comma first:
if b64_string.startswith("data:"):
b64_string = b64_string.split(",", 1)[1]
Not sure what kind of file it is? The first few characters tell you: JVBERi0 is a PDF, iVBORw0KGgo a PNG, /9j/ a JPEG, UEsDB a zip (including .docx and .xlsx). The file-signature table lists 40+ formats.
For a large Base64 file, base64.decode() streams from one binary file object to another, so the whole thing never sits in memory as a string:
import base64
with open("input.b64", "rb") as src, open("output.bin", "wb") as dst:
base64.decode(src, dst)
And for a quick one-off, the module has a command-line mode:
python3 -m base64 -d input.b64 > output.bin
Decoding a JWT payload
A JWT is three URL-safe, unpadded Base64 segments separated by dots. The middle one is JSON. Combine the two fixes above:
import base64, json
def jwt_payload(token: str) -> dict:
seg = token.split(".")[1]
seg += "=" * (-len(seg) % 4)
return json.loads(base64.urlsafe_b64decode(seg))
This only reads the token. It does not check the signature, so never use the result to make an access decision. Use a library such as PyJWT for that. To inspect a token without writing code, use the JWT decoder.
Not sure the decode worked? Paste the original string into the decoder. It shows the text, the hex bytes and the detected file type side by side, so you can compare it with what your code produced. Nothing is uploaded; it runs in your browser.
Published 9 November 2026. Spot an error? Email contactus@base64decode.tools.
Common questions.
Because Base64 can encode any data, not just text. Python can't know whether the bytes are UTF-8 text, Latin-1 text or a PNG image. Call .decode("utf-8") yourself when you know the content is UTF-8 text.
The string is missing its trailing = characters. Append them with s + "=" * (-len(s) % 4) before decoding. If that still fails, the string was probably truncated or contains characters from a different alphabet.
b64decode expects the standard alphabet with + and /. urlsafe_b64decode expects the URL-safe alphabet with - and _, used by JWTs and many tokens. With default settings b64decode silently drops - and _, so using it on URL-safe input gives wrong results.
Open the output file in binary mode and write the decoded bytes: open("out.pdf", "wb").write(base64.b64decode(s)). Strip any data: URI prefix first, and do not call .decode() on binary data.
Yes. python3 -m base64 -d input.b64 decodes a file to standard output, so you can redirect it to a file with > output.bin.