The base64 module have functions which helps to encode the text or binary data into base64 format and decode the base64 data into text or binary data. The base64 module is used to encode and decode the data in the following ways:
The base64 module provides the
b64encode() function. It encodes a bytes-like object using Base64 and returns the encoded bytes. Let's see how to use this function.
Note: Since we start with a string, we encode it first to a byte-like object using string.encode(). Later we convert it back to a string using string.decode(). This articles teaches more about the difference between byte objects and strings in Python.
import base64 data = "Python is a programming language" data_bytes = data.encode('ascii') base64_bytes = base64.b64encode(data_bytes) base64_string = base64_bytes.decode('ascii') print("Encoded Data: ", base64_string) # Output: Encoded Data: UHl0aG9uIGlzIGEgcHJvZ3JhbW1pbmcgbGFuZ3VhZ2U=
In the above example, first we convert the input string to byte-like objects and then encode those byte-like objects to base64 format.
Decoding base64 string is opposite to that of encoding. The base64 module provides the
b64decode() function which decodes the Base64 encoded bytes-like object or ASCII string and returns the decoded bytes. Let's see how to use this function.
import base64 base64_string = "UHl0aG9uIGlzIGEgcHJvZ3JhbW1pbmcgbGFuZ3VhZ2U=" base64_bytes = base64_string.encode('ascii') data_bytes = base64.b64decode(base64_bytes) data = data_bytes.decode('ascii') print("Decoded Data:", data) # Output: Decoded Data: Python is a programming language
In the above example, first we convert the base64 strings into unencoded data bytes and then decode those bytes to get the original string.
Note: To prevent data corruption, make sure to use the same encoding format when converting from string to bytes, and from bytes to string.
In this tutorial, we have learned the basics of base64 encoding and decoding in Python. If you want to learn more about base64 encoding and decoding, you can visit the official documentation of the base64 module.