How do I return a base64 encoded string given a string? How do I decode a base64 encoded string into a string?

 

To encode a string as a Base64 encoded string in Python, you can use the base64 module's b64encode() function. To decode a Base64 encoded string back to a regular string, you can use the base64 module's b64decode() function. Here's an example:

Encoding a String to Base64:

python
import base64 # Input string text = "Hello, World!" # Encode the string 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 import the base64 module.

  • We have an input string text that we want to encode as Base64.

  • We use text.encode("utf-8") to convert the input string to bytes using the UTF-8 encoding.

  • We use base64.b64encode() to encode the bytes as a Base64 encoded byte array.

  • To convert the encoded byte array back to a string, we use encoded_bytes.decode("utf-8"). This step is optional and depends on whether you want the result as bytes or as a string.

Decoding a Base64 Encoded String:

python
import base64 # Base64 encoded string encoded_str = "SGVsbG8sIFdvcmxkIQ==" # Decode the Base64 encoded 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 that we want to decode.

  • We use base64.b64decode() to decode the Base64 encoded string into bytes.

  • We use decoded_bytes.decode("utf-8") to convert the decoded bytes back to a string using the UTF-8 encoding.

These examples demonstrate how to encode a string as a Base64 encoded string and decode a Base64 encoded string back to a regular string using the base64 module in Python.

Comments