Base64 Encode in Python

Encode a string to Base64 in Python with base64.b64encode. Remember to encode to bytes first and decode the result. Verify with the online encoder.

Part of the free Base64 Encoder. Runs in your browser — nothing is uploaded.

Base64 Encode in Python

Python's base64.b64encode works on bytes, not strings, and returns bytes. That is why the usual idiom encodes the string first and decodes the result afterwards. Check the expected output below.

Worked example: The idiomatic Python version

Python

import base64
base64.b64encode('Hello, World!'.encode('utf-8')).decode('ascii')

Result

SGVsbG8sIFdvcmxkIQ==

Practical tip

For URL-safe output use base64.urlsafe_b64encode. To strip padding, call .rstrip(b"=") on the bytes before decoding.

How to use this Base64 Encoder

  1. 1Use the live tool above — it runs entirely in your browser and never uploads your data.
  2. 2Paste the sample from the worked example, or use your own input.
  3. 3Copy the result, then adapt the same steps in your editor, script, or pipeline.

Base64 Encode in Python FAQs

Why do I get TypeError: a bytes-like object is required?

b64encode needs bytes. Call .encode("utf-8") on your string before passing it in.

How do I decode in Python?

base64.b64decode(encoded).decode("utf-8") returns the original string.