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.
Calling base64.b64encode on a string raises an error, and the result of a call that works is not a string either.
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))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.