How can I decode Base64-encoded data in Python using the Base64 module?

How can I decode Base64-encoded data in Python using the Base64 module? I’m trying to extract information from Base64-encoded data, but the module doesn’t seem to be working as expected. What steps should I follow to fix this issue?

The most straightforward way to decode Base64 data in Python is by using the base64 module’s b64decode function.

Here’s an example:

import base64

# Example base64 encoded data
encoded_data = 'SGVsbG8gd29ybGQh'  # Base64 encoded 'Hello world!'

# Decode the data
decoded_data = base64.b64decode(encoded_data)

# Convert the decoded byte data to a string
decoded_string = decoded_data.decode('utf-8')

print(decoded_string)  # Output: Hello world!

If your Base64 data is URL-safe or uses filename-safe encoding (with characters like - and _ instead of + and /), you can use base64.urlsafe_b64decode:

import base64

# Example URL-safe base64 encoded data
encoded_data = 'SGVsbG8gd29ybGQh'  # This is URL-safe in this case

# Decode the data
decoded_data = base64.urlsafe_b64decode(encoded_data)

# Convert the decoded byte data to a string
decoded_string = decoded_data.decode('utf-8')

print(decoded_string)  # Output: Hello world!