base64
The base64 library encodes and decodes data using standard Base64, with Python-compatible function names. Inputs may be a bytes value or a string (UTF-8 encoded); decoding always returns a bytes value, so call .decode() on the result if you need a string.
Available Functions
| Function | Description |
|---|---|
b64encode(s) |
Encode a bytes or str value to a Base64 str. |
b64decode(s) |
Decode a Base64 str, returning bytes; raises if s is not valid Base64. |
Example
import base64
encoded = base64.b64encode("hello world") # str input is UTF-8 encoded first
print(encoded) # aGVsbG8gd29ybGQ=
print(base64.b64encode(b"hello world") == encoded) # True
decoded = base64.b64decode(encoded) # always bytes
print(decoded) # b'hello world'
print(decoded.decode()) # hello worldDifferences from Python
b64encode()accepts astr(encoded as UTF-8) and returns astr, where Python requires and returnsbytes.b64decode()requires astrand raises on invalid input (Python silently discards invalid characters by default).- Only standard Base64 is provided; there is no
urlsafe_b64encode,b32encode,b16encodeora85encode.