Base64 Decoding in Python

Python’s base64 module provides functions to perform Base64 encoding and decoding as described in RFC 3548.

This article contains examples that demonstrate how to decode any Base64 encoded data back to binary data. To learn how to encode binary data to Base64 encoded format, check out this article.

Python Base64 Decode Example

import base64

encodedStr = "aGVsbG8gd29ybGQxMjMhPyQ="

# Standard Base64 Decoding
decodedBytes = base64.b64decode(encodedStr)
decodedStr = str(decodedBytes, "utf-8")

print(decodedStr)   # hello world123!?$

Python Base64 URL safe Decode Example

The URL and Filename safe Base64 decoding is similar to the standard Base64 decoding except that it works with Base64’s URL and Filename safe Alphabet which uses hyphen (-) in place of + and underscore (_) in place of / character.

import base64

encodedStr = "aGVsbG8gd29ybGQxMjMhPyQ="

# Url Safe Base64 Decoding
decodedBytes = base64.urlsafe_b64decode(encodedStr)
decodedStr = str(decodedBytes, "utf-8")

print(decodedStr)   # hello world123!?$

Also Read: Python Base64 Encode Example

References