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().

base64 functionPython 2.4+Live demo
Common call
base64.b64encode(text.encode()).decode('ascii')
Returns
bytes such as b'aGk=' — decode('ascii') for a str
Replaces
Hand-written bit shifting; codecs.encode(data, "base64") (which adds newlines)
Watch out
Passing a str raises TypeError; the result is bytes
base64.b64encode(ss — The data to encode: bytes, bytearray or memoryview. A str raises TypeError — encode it first.type: bytes-like · required, altcharsaltchars — Exactly 2 bytes that replace + and / in the output, e.g. b'-_'. Any other length fails an assert (AssertionError).type: bytes · default: None=None)
→ bytes

Demo

Live evaluation
The full recipe for text: UTF-8 bytes in, ASCII str out.
Try:
Inputs
textstrany text
Code
import base64
base64.b64encode('hello world'.encode()).decode('ascii')
Result
'aGVsbG8gd29ybGQ='

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

NameTypeRequiredDescription
sbytes-likeyesThe data to encode: bytes, bytearray or memoryview. A str raises TypeError — encode it first.
altcharsbytesno (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

Text to Base64 text
The one-liner most code needs.
import base64
encoded = base64.b64encode(text.encode('utf-8')).decode('ascii')
A file to Base64
Open in binary mode ('rb') — the bytes go straight in.
import base64
with open('photo.jpg', 'rb') as f:
    encoded = base64.b64encode(f.read()).decode('ascii')
Base64 inside JSON
json cannot hold bytes; the decoded Base64 str can.
import base64, json
payload = json.dumps({'file': base64.b64encode(data).decode('ascii')})

Examples

1. Bytes in, bytes out
import base64 base64.b64encode(b'hello')
Returns
b'aGVsbG8='
2. Get a str
import base64 base64.b64encode(b'hello').decode('ascii')
Returns
'aGVsbG8='
3. UTF-8 text
import base64 base64.b64encode('Zoë'.encode('utf-8'))
Returns
b'Wm/Dqw=='
4. Padding by length
import base64 [base64.b64encode(b'a'), base64.b64encode(b'ab'), base64.b64encode(b'abc')]
Returns
[b'YQ==', b'YWI=', b'YWJj']
5. No line breaks, ever
import base64 b'\n' in base64.b64encode(bytes(1000))
Returns
False
6. Size grows by a third
import base64 len(base64.b64encode(bytes(300)))
Returns
400
7. altchars
import base64 base64.b64encode(b'\xfb\xff', altchars=b'-_')
Returns
b'-_8='
8. str is rejected
import base64 base64.b64encode('hello')
Returns
TypeError: a bytes-like object is required, not 'str'

Pitfalls

1. Passing a str
Base64 encodes bytes. Choose the text encoding yourself (almost always UTF-8) with .encode().
b64encode(str)
import base64
base64.b64encode('héllo')
TypeError: a bytes-like object is required, not 'str'
b64encode(str.encode())
import base64
base64.b64encode('héllo'.encode())
b'aMOpbGxv'
2. Using str() on the result
str(b'...') is the repr with the b prefix and quotes. Decode the ASCII bytes instead.
str()
import base64
str(base64.b64encode(b'hi'))
"b'aGk='"
.decode('ascii')
import base64
base64.b64encode(b'hi').decode('ascii')
'aGk='
3. Encoding twice
Calling b64encode on something that is already Base64 encodes the Base64 text again — the result decodes to Base64, not to your data.
double encode
import base64
base64.b64encode(base64.b64encode(b'hi'))
b'YUdrPQ=='
encode once
import base64
base64.b64encode(b'hi')
b'aGk='

When to use

Use it
  • Sending binary data through JSON, XML, HTTP headers, data: URIs or email bodies
  • Any API that asks for "Base64" with + and /
Reach for something else
  • URLs, file names, JWTs → urlsafe_b64encode
  • MIME / PEM with 76-character lines → encodebytes
  • Hiding secrets — Base64 is not encryption

Notes

CPython impl
binascii.b2a_base64(s, newline=False) in C, then bytes.translate() when altchars is given
Length
Output is 4 × ceil(len(s) / 3) bytes
Exceptions
TypeError for str or other non-bytes input; AssertionError when altchars is not 2 bytes long (and the check disappears under python -O)

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.