all Python 3binasciifunction
binascii.a2b_base64()
base64
Decodes base64 to bytes. By default it silently skips stray characters; strict_mode=True (3.11+) demands strict RFC 4648.
Syntax
binascii.a2b_base64(string, /, *, strict_mode=False)
Lenient mode forgives spaces, newlines and junk, which helps with email but is risky for input validation: 'aG k=' decodes without complaint. Missing '=' at the end raises binascii.Error 'Incorrect padding', a common issue with base64 from URLs where '=' was trimmed; append '=' * (-len(s) % 4) to fix it. It also accepts ASCII str.
Examples
import binascii
print(binascii.a2b_base64('aG k=\n')) # → b'hi'
s = 'aGk'
print(binascii.a2b_base64(s + '=' * (-len(s) % 4))) # → b'hi'
try:
binascii.a2b_base64(s)
except binascii.Error as e:
print(e) # → Incorrect padding
# Python 3.11+
import binascii
try:
binascii.a2b_base64('aG k=', strict_mode=True)
except binascii.Error as e:
print(e) # → Only base64 data is allowed
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy