all Python 3base64function
base64.b64encode()
Base64
Encodes bytes as Base64, text made of 64 safe characters for carrying binary data through JSON, e-mail or data URLs.
Syntax
base64.b64encode(s, altchars=None)
Base64 is not encryption: anyone decodes it without a key, so hiding passwords with it is pointless. The function takes only bytes and returns bytes too: encode a string with .encode('utf-8') first, and .decode('ascii') the result for JSON. The size grows by a third, and the trailing '=' is padding to a multiple of 4. For URLs use urlsafe_b64encode: '+' and '/' break there.
Examples
import base64
data = 'привет'.encode('utf-8')
enc = base64.b64encode(data)
print(enc) # → b'0L/RgNC40LLQtdGC'
print(enc.decode('ascii')) # → 0L/RgNC40LLQtdGC
import base64
print(base64.b64encode(b'a'), base64.b64encode(b'ab'), base64.b64encode(b'abc')) # → b'YQ==' b'YWI=' b'YWJj'
try:
base64.b64encode('hi')
except TypeError as e:
print(type(e).__name__) # → TypeError
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy