A Simple Guide to Python Base64 Encode String for Beginners – Python Tutorial

By | August 11, 2019

In this tutorial, we will introduce how to use base64 model to encode and decode a python string, there are some tips you shoud notice and you can learn how to use base64 library by following our tutorial.

python base64 tutorials and examples

Base64 basic encode and decode function

base64.b64encode(s, altchars=None)
base64.b64decode(s, altchars=None, validate=False)

You shoud notice these two function input is bytes-like object, the return is byte.

So to encode a string you shoud:

1.Convert string to byte object

2.Use base64.b64encode() to encode byte object

3.Convert byte object to string

Then we create a function to encode a python string with base64.

Import library

import base64

Encode python string

def base64_encode(str):
    byte_str = str.encode()
    base64_str= base64.b64encode(byte_str)
    base64_str = base64_str.decode()
    return base64_str

As to encode, we also can create a function to decode it.

Decode base64 string

def base64_decode(base64_str):
    byte_str = base64_str.encode()
    str = base64.b64decode(byte_str)
    str = str.decode()
    return str

How to use?

s = 'https://www.tutorialexample.com/'    
base64_str = base64_encode(s)
print(base64_str)

str = base64_decode(base64_str)
print(str)

The output is:

aHR0cHM6Ly93d3cudHV0b3JpYWxleGFtcGxlLmNvbS8=
https://www.tutorialexample.com/

Leave a Reply

Your email address will not be published. Required fields are marked *