How To Decode Base64 Using Python

In this tutorial, we’ll learn how to decode Base64 using Python programming language. Base64 is a popular encoding algorithm that represents binary data using ASCII characters. It is often used to embed images in emails and encode user authentication in the HTTP header. Python has a built-in library called base64 that provides the necessary tools for decoding this encoding format.

Step 1: Import the base64 Library

First, we need to import the base64 library, which is a part of the Python standard library.

Step 2: Prepare the Base64 Encoded String

Let’s encode a sample text string into Base64 format. For demonstration purposes, we’ll use the string “Hello, World!”, but you can replace it with any other string (or binary data) to decode.

In Python, we typically represent Base64 encoded strings using bytes, hence the b prefix used with the string.

Step 3: Decode the Base64 String

Now, we’ll use the base64.b64decode() function to decode the encoded string. The function takes the encoded data as its argument and returns the decoded data.

Step 4: Print the Decoded String

Finally, let’s print the decoded data as a string to verify if we decoded it correctly.

It is necessary to call the decode() function with the argument "utf-8" on the decoded bytes to convert the binary data into a human-readable format.

Full Code

Now let’s put all pieces together to form the complete code.

Output

Hello, World!

Conclusion

In this tutorial, we’ve successfully learned how to decode a Base64 string using Python. The base64 library makes it easy to work with this popular encoding format for various real-life applications such as email attachments, authentication tokens, and more.