Python Glossary Русский

all Python 3base64function

base64.b64decode()

Base64

Decodes Base64 back to bytes. It accepts bytes or an ASCII string; by default it silently drops foreign characters.

Syntax

base64.b64decode(s, altchars=None, validate=False)

Without validate=True, garbage in the input (spaces, '!', newlines) is simply dropped, and corrupted data decodes successfully. A URL-safe string is worse: '-' and '_' are dropped too, and you get different bytes with no error at all; it needs urlsafe_b64decode. Wrong '=' padding gives binascii.Error, a subclass of ValueError. The result is bytes; get text with .decode('utf-8').

Examples

import base64
print(base64.b64decode('0L/RgNC40LLQtdGC').decode('utf-8'))  # → привет
print(base64.b64decode(b'aG!!k/P g=='))  # → b'hi?>' — мусор выброшен молча
import base64
import binascii
try:
    base64.b64decode(b'aG!!k/Pg==', validate=True)
except binascii.Error as e:
    print(type(e).__name__, isinstance(e, ValueError))  # → Error True
import base64
print(base64.b64decode(b'ab-_cd=='))  # → b'i\xb7\x1d' — '-' и '_' выброшены, данные другие
print(base64.urlsafe_b64decode(b'ab-_cd=='))  # → b'i\xbf\xbfq'

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy