Base64 Encoding in Python
Our first program will demonstrate base64 encoding and decoding. Here’s the full source code:
To run the program, save the code in a file named base64_encoding.py
and use the Python interpreter:
The string encodes to slightly different values with the standard and URL-safe base64 encoders (trailing +
vs -
) but they both decode to the original string as desired.
In Python, the base64
module provides the necessary functions for base64 encoding and decoding. The b64encode
and b64decode
functions are used for standard base64, while urlsafe_b64encode
and urlsafe_b64decode
are used for URL-safe base64.
Note that in Python, we need to encode the string to bytes before encoding to base64, and decode the result back to a string. This is because base64 operations work on byte-like objects.
The try
-except
blocks are used to handle potential decoding errors, although in this case, we know our input is well-formed.