Learn how to python base64 encode in this tutorial below.

Python comes with the base64 module, but how do you use it?

You start by including the module:

import base64

But you would probably expect to just do something like print( base64.b64encode('something' )), but this will throw an error and complain about:

TypeError: a bytes-like object is required, not 'str'

How to Base64 Encode a String?

You can either do one of the following:

import base64
encoded = base64.b64encode('data to be encoded'.encode('ascii'))
print(encoded)

..or more simply:

import base64
encoded = base64.b64encode(b'data to be encoded')
print(encoded)

Either way, you will end up with a b'ZGF0YSB0byBiZSBlbmNvZGVk' byte string response

Base64 Encoding Exotic Characters

If your string contains ‘exotic characters’, it may be safer to encode it with utf-8:

encoded = base64.b64encode (bytes('data to be encoded', "utf-8"))

To decode this range, you could do something like this:

import base64

a = base64.b64encode(bytes(u'complex string: ñáéíóúÑ', "utf-8"))
# a: b'Y29tcGxleCBzdHJpbmc6IMOxw6HDqcOtw7PDusOR'

b = base64.b64decode(a).decode("utf-8", "ignore")
print(b)
# b :complex string: ñáéíóúÑ

By using these solutions, it is simple to python base64 encode.

Why do I need ‘b’ to encode a string with Base64?

This is because base64 encoding takes in 8-bit binary byte data and then encodes it by using a range of character which include the following:

A-Za-z0-9+/*

This is in order to be able to transmit the payload over various channels that don’t preserve the 8-bits of data.

An example of this is email.

Therefore, you need to use Python’s b'' syntax to make it a string of 8-bit bytes. Without the b'' it will simply be a standard string.

An important note to be aware of is that a string in Python is a sequence of Unicode characters.