How do I encode and decode a base64 string?

 

You can encode and decode a Base64 string in Python using the built-in base64 module. Here's an example that demonstrates both encoding and decoding:

Encoding a String to Base64:

python
import base64 # Text to be encoded text = "Hello, World!" # Encode the text to Base64 encoded_bytes = base64.b64encode(text.encode("utf-8")) encoded_str = encoded_bytes.decode("utf-8") print("Encoded Base64:", encoded_str)

In this example, we first import the base64 module. Then, we define the text variable containing the string we want to encode. We use text.encode("utf-8") to convert the string to bytes and then use base64.b64encode() to encode those bytes to Base64. Finally, we decode the result back to a string using encoded_bytes.decode("utf-8").

Decoding a Base64 String:

python
import base64 # Base64 string to be decoded encoded_str = "SGVsbG8sIFdvcmxkIQ==" # Decode the Base64 string decoded_bytes = base64.b64decode(encoded_str) decoded_str = decoded_bytes.decode("utf-8") print("Decoded String:", decoded_str)

In this example, we have a Base64-encoded string (encoded_str). We use base64.b64decode() to decode it into bytes and then use decoded_bytes.decode("utf-8") to convert those bytes back to a string.

Keep in mind that Base64 encoding is commonly used to encode binary data, such as images or files, to a text-based format. When decoding a Base64 string, make sure that the original data was encoded as Base64; otherwise, the decoding process may not produce meaningful results.

Comments