How to Base64 Encode a String in Python

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

You start by including the module:

import base64
Code language: Python (python)

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)
Code language: Python (python)

..or more simply:

import base64 encoded = base64.b64encode(b'data to be encoded') print(encoded)
Code language: Python (python)

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"))
Code language: Python (python)

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: ñáéíóúÑ
Code language: Python (python)
Notify of
Inline Feedbacks
View all comments