write a code to encode and decode a string in python

Write a code to encode and decode a string in python



To encode and decode a string in Python, you can use the built-in b64encode and b64decode functions from the base64 module. These functions allow you to encode and decode a string using base64 encoding, which is a standard for representing binary data in an ASCII string format.

Here is an example of how you might use these functions to encode and decode a string in Python:

import base64

def encode(string):
    return base64.b64encode(string.encode()).decode()

def decode(string):
    return base64.b64decode(string.encode()).decode()

string = "Hello, world!"
encoded_string = encode(string)
print(encoded_string) # Outputs "SGVsbG8sIHdvcmxkIQ=="
decoded_string = decode(encoded_string)
print(decoded_string) # Outputs "Hello, world!"

In this example, the encode function takes a string as input and returns the base64-encoded version of the string. It does this by first encoding the string as a bytes object using the encode method, and then encoding the bytes object as a base64-encoded string using the b64encode function. The decode function works in the opposite way, taking a base64-encoded string as input and returning the original string.

Post a Comment

0 Comments