In Python 3, to encode text to base64, you will need to use the base64 module. This module provides functions to encode and decode data in base64 format.

First, we must import the specified module into our code.

import base64

Next, we will establish a variable to hold the text that we intend to encode.

name = "John Doe"

The next step involves converting the variable ‘name’ into a bytes object. This conversion will enable us to work with the ‘name’ variable in a format suited for our needs.

name_bytes = name.encode()

After you have encoded the data, the next step is to use the base64 module to convert the obtained bytes object from the previous step.

name_b64_bytes = base64.b64encode(name_bytes)

Afterwards, we convert the obtained bytes object into a base64 string.

name_b64_str = name_b64_bytes.decode()

To convert it back to a string

We use the base64 module to decode the base64 string.

name_b64_bytes = base64.b64decode(name_b64_str)

When we receive the result, it is in the form of a bytes object. In order to work with it as a string, we need to convert it by using the following line of code:

name_b64_str = name_b64_bytes.decode()

Here is the full code:

import base64

name = "John Doe"

name_bytes = name.encode()

name_b64_bytes = base64.b64encode(name_bytes)

name_b64_str = name_b64_bytes.decode()

# To convert back to string

name_b64_bytes = base64.b64decode(name_b64_str)

name_b64_str = name_b64_bytes.decode()

print(name_b64_str)

Tagged in:

, ,