The right way to Base64 Encode a String in Python

Discover ways to python base64 encode on this tutorial under.

Python comes with the base64 module, however how do you employ it?

You begin by together with the module:

import base64

However you’d most likely anticipate to simply do one thing like print( base64.b64encode('one thing' )), however this may throw an error and complain about:

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

The right way to Base64 Encode a String?

You’ll be able to both do one of many following:

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

..or extra merely:

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

Both means, you’ll find yourself with a b'ZGF0YSB0byBiZSBlbmNvZGVk' byte string response

Base64 Encoding Unique Characters

In case your string accommodates ‘unique characters’, it might be safer to encode it with utf-8:

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

To decode this vary, you would do one thing like this:

import base64

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

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

Through the use of these options, it’s easy to python base64 encode.

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

It’s because base64 encoding takes in 8-bit binary byte information after which encodes it by utilizing a variety of character which embrace the next:


That is so as to have the ability to transmit the payload over varied channels that don’t protect the 8-bits of information.

An instance of that is e mail.

Subsequently, you have to use Python’s b'' syntax to make it a string of 8-bit bytes. With out the b'' it should merely be a regular string.

See also  Kind Lexicographical Order of Substrings in Java

An essential notice to concentrate on is {that a} string in Python is a sequence of Unicode characters.

Leave a Reply