Skip to content
shellhacks.dev
Python

Base64 encode a string

Encode with base64.b64encode(), which takes and returns bytes, so encode the string first and decode the result. The URL-safe variant swaps two characters.

1 min read
Summarize in AI

Calling base64.b64encode on a string raises an error, and the result of a call that works is not a string either.

Python
import base64

text = "héllo"
encoded = base64.b64encode(text.encode("utf-8"))
print(encoded)
print(encoded.decode("ascii"))
print(base64.b64decode(encoded).decode("utf-8"))
try:
    base64.b64encode(text)
except TypeError as e:
    print("TypeError:", e)
data = b"\xfb\xff\xfe"
print(base64.b64encode(data), base64.urlsafe_b64encode(data))
Text
b'aMOpbGxv'
aMOpbGxv
héllo
TypeError: a bytes-like object is required, not 'str'
b'+//+' b'-__-'

Base64 maps bytes to text, so the function needs bytes in and gives bytes out. A string must be turned into bytes with an explicit encoding first, and the result is decoded as ASCII to get text back, as the base64 documentation shows. The error message in the output is what a string argument produces. The last line shows the URL-safe form, which uses a dash and a low line in place of the plus and the slash.

The standard form pads with equals signs, and the URL-safe form keeps the padding, so strip it with rstrip("=") for tokens in URLs and add it back before decoding. Base64 is an encoding, not encryption. On the command line, base64 -w0 is the shell equivalent, and its default wraps lines at 76 characters.

Share

More snippets

Python

Read a CSV file

Read a CSV file with csv.reader and open it with newline=''. Without that argument a line break inside a quoted field is changed before the parser sees it.

2 min read
Python

Convert a timestamp

Convert a Unix timestamp with datetime.fromtimestamp(ts, tz=timezone.utc). Without tz it uses the machine's zone, and milliseconds need a division by 1000.

1 min read
Python

Generate a UUID

Generate a random UUID with uuid.uuid4() and a repeatable one with uuid.uuid5(namespace, name). The hex attribute gives the form without hyphens.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.