In Python, you can decode a Base64 encoded string using the base64
package.
Using base64.b64decode()
This is the standard and most straightforward method using the base64
module.
import base64
encoded_data = 'SGVsbG8sIFdvcmxkIQ=='
decoded_data = base64.b64decode(encoded_data)
print(decoded_data.decode('utf-8')) # Output: Hello, World!
Using base64.urlsafe_b64decode()
If your Base64 encoded data is URL-safe, meaning it uses -
instead of +
and _
instead of /
, you should use urlsafe_b64decode()
. This function is similar to b64decode()
but supports URL and filesystem safe alphabet.
import base64
encoded_data = 'SGVsbG8sIFdvcmxkIQ=='.replace('+', '-').replace('/', '_') # Making it URL-safe for demonstration
decoded_data = base64.urlsafe_b64decode(encoded_data)
print(decoded_data.decode('utf-8')) # Output should still be: Hello, World!