Encoding and Decoding Base64 Strings in Python

Base64 encoding is used to convert strings containing text and numerical data into ASCII characters. This is useful when transferring information across a network that might interpret only text characters or otherwise corrupt non-ASCII characters.

 

In this tutorial, we will learn how to encode and decode base64 strings in Python using examples.

 

Encoding base64 Strings

Before we can base64 encode a string in python we must import the base64 module. Then we can go ahead and convert the string to a bytes object be finally encoding it.

 

import base64

string = 'hello world'

str_bytes = string.encode('ascii')
str_base64 = base64.b64encode(str_bytes)

print(str_base64)
b'aGVsbG8gd29ybGQ='

 

In the example above we are converting the string into an ASCII bytes object using the Python encode() method, then converting that into base64 using the b64encode() method of the base64 package and printing the result.

 

Decoding base64 Strings

To decode a base64 string we will follow the same process as encoding except in reverse. We will first get the ASCII bytes by using the b64decode method from the base64 package and then decode the ASCII bytes object using the Python decode() method.

 

import base64

string = 'hello world'

str_bytes = string.encode('ascii')
str_base64 = base64.b64encode(str_bytes)

# decoding:

str_b = base64.b64decode(str_base64)

result = str_b.decode('ascii')

print(result)
hello world

 

The important thing to watch out for when decoding is that the Python decode() method is run in ASCII mode otherwise the data could get corrupted.

 

Conclusion

You now know how to base64 encode and decode in Python and why it is important to use it for some applications.

encode decode base64