base64.b64encode
The workhorse encoder. It takes bytes, not str, and gives back bytes, not str — so "Base64-encode a string" is always encode() → b64encode() → decode().
Demo
import base64 base64.b64encode('hello world'.encode()).decode('ascii')
The output length is always 4 × ceil(n / 3): "a" becomes YQ== and "abc" becomes YWJj with no padding at all. Non-ASCII text is encoded as UTF-8 first, so "Zoë 🙂" (5 characters) is 9 bytes and 12 Base64 characters. altchars must be exactly 2 bytes — a single character fails an assert, so the error line is just AssertionError: b'-'.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| s | bytes-like | yes | The data to encode: bytes, bytearray or memoryview. A str raises TypeError — encode it first. |
| altchars | bytes | no (None) | Exactly 2 bytes that replace + and / in the output, e.g. b'-_'. Any other length fails an assert (AssertionError). |
Return value
bytes — The Base64 text as ASCII bytes, padded with = to a multiple of 4 characters, without a trailing newline.
Common patterns
import base64 encoded = base64.b64encode(text.encode('utf-8')).decode('ascii')
import base64 with open('photo.jpg', 'rb') as f: encoded = base64.b64encode(f.read()).decode('ascii')
import base64, json payload = json.dumps({'file': base64.b64encode(data).decode('ascii')})
Examples
Pitfalls
import base64 base64.b64encode('héllo')
import base64 base64.b64encode('héllo'.encode())
import base64 str(base64.b64encode(b'hi'))
import base64 base64.b64encode(b'hi').decode('ascii')
import base64 base64.b64encode(base64.b64encode(b'hi'))
import base64 base64.b64encode(b'hi')
When to use
- Sending binary data through JSON, XML, HTTP headers, data: URIs or email bodies
- Any API that asks for "Base64" with + and /
- URLs, file names, JWTs → urlsafe_b64encode
- MIME / PEM with 76-character lines → encodebytes
- Hiding secrets — Base64 is not encryption
Notes
FAQ
base64.b64encode(s.encode('utf-8')).decode('ascii'). The encode step picks the byte representation of the text; the decode step turns the ASCII result into a str.