;

How to Encode and Decode String With Base64 in Python


Tutorialsrack 13/02/2022 Python

In this article, you will learn how to encode and decode strings with base64 in Python. We will import the base64 module and use the base64.b64encode() method to encode the string and base64.b64decode() method to decode the string. 

Here are the examples to encode the plain text to Base64 and decode the plain text from Base64 using Python.

Encoding String to Base64

import base64

plain_text = "Hello, TutorialsRack!"
ascii_data = plain_text.encode('ascii')
base64_byte_data = base64.b64encode(ascii_data)

encoded_data = base64_byte_data.decode('ascii')

print("Base64 Encoded String: "+ encoded_data)
# Output ==> Base64 Encoded String: SGVsbG8sIFR1dG9yaWFsc1JhY2sh

Decoding String From Base64

import base64

base64_str = 'SGVsbG8sIFR1dG9yaWFsc1JhY2sh'
base64_bytes = base64_str.encode('ascii')
decoded_bytes_data = base64.b64decode(base64_bytes)
decoded_data = decoded_bytes_data.decode('ascii')

print("Base64 Decoded String: "+ decoded_data)
# Output ==> Hello, TutorialsRack!

I hope this article will help you to understand how to encode and decode strings with base64 in Python.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags