The base64 Module

The base64 Module
Parameter Description

base64.b64encode(s, altchars=None)
s A bytes-like object
A bytes-like object of length 2+ of characters to replace the
altchars '+' and '=' characters when creating the Base64 alphabet.
Extra characters are ignored.
base64.b64decode(s, altchars=None,
validate=False)
s A bytes-like object
A bytes-like object of length 2+ of characters to replace the
altchars '+' and '=' characters when creating the Base64 alphabet.
Extra characters are ignored.
If validate is True, the characters not in the normal Base64
validate alphabet or the alternative alphabet are not discarded
before the padding check
base64.standard_b64encode(s)
s A bytes-like object
base64.standard_b64decode(s)
s A bytes-like object
base64.urlsafe_b64encode(s)
s A bytes-like object
base64.urlsafe_b64decode(s)

s

b32encode(s)

s

b32decode(s)

s

base64.b16encode(s)

s

base64.b16decode(s)

s

base64.a85encode(b, foldspaces=False, wrapcol=0, pad=False, adobe=False)

b

foldspaces

wrapcol

pad

adobe

base64.a85decode(b, foldspaces=False, adobe=False, ignorechars=b'\t\n\r\v')

A bytes-like object

A bytes-like object

A bytes-like object

A bytes-like object

A bytes-like object

A bytes-like object

If foldspaces is True, the character ‘y’ will be used instead of 4 consecutive spaces.

The number characters before a newline (0 implies no newlines)

If pad is True, the bytes are padded to a multiple of 4 before encoding

If adobe is True, the encoded sequenced with be framed with ‘<~’ and ”~>’ as used with Adobe products

b A bytes-like object
foldspaces If foldspaces is True, the character 'y' will be used instead
of 4 consecutive spaces.

adobe

ignorechars

base64.b85encode(b, pad=False)

If adobe is True, the encoded sequenced with be framed with ‘<~’ and ”~>’ as used with Adobe products

A bytes-like object of characters to ignore in the encoding process

b

pad

base64.b85decode(b)

A bytes-like object

If pad is True, the bytes are padded to a multiple of 4 before encoding

b A bytes-like object

Base 64 encoding represents a common scheme for encoding binary into ASCII string format using radix 64. The base64 module is part of the standard library, which means it installs along with Python. Understanding of bytes and strings is critical to this topic and can be reviewed here. This topic explains how to use the various features and number bases of the base64 module.

base64 Module: Encoding and Decoding Base64

To include the base64 module in your script, you must import it first:

import base64

The base64 encode and decode functions both require a bytes-like object. To get our string into bytes, we must encode it using Python’s built in encode function. Most commonly, the UTF-8 encoding is used, however a full list of these standard encodings (including languages with different characters) can be found here in the official Python Documentation. Below is an example of encoding a string into bytes:

s = "Hello World!"
b = s.encode("UTF-8")

The output of the last line would be:

b'Hello World!'

The b prefix is used to denote the value is a bytes object.

To Base64 encode these bytes, we use the base64.b64encode() function:

import base64
s = "Hello World!"
b = s.encode("UTF-8")
e = base64.b64encode(b)
print(e)

That code would output the following:

b'SGVsbG8gV29ybGQh'

which is still in the bytes object. To get a string out of these bytes, we can use Python’s decode() method with the

UTF-8 encoding:

import base64
s = "Hello World!"
b = s.encode("UTF-8")
e = base64.b64encode(b)
s1 = e.decode("UTF-8")
print(s1)

The output would then be:

SGVsbG8gV29ybGQh

If we wanted to encode the string and then decode we could use the base64.b64decode() method:

import base64
Creating a string s = "Hello World!"
Encoding the string into bytes b = s.encode("UTF-8")
Base64 Encode the bytes
e = base64.b64encode(b)
Decoding the Base64 bytes to string s1 = e.decode("UTF-8")
Printing Base64 encoded string print("Base64 Encoded:", s1)
Encoding the Base64 encoded string into bytes b1 = s1.encode("UTF-8")
Decoding the Base64 bytes
d = base64.b64decode(b1)
Decoding the bytes to string s2 = d.decode("UTF-8") print(s2)

As you may have expected, the output would be the original string:

Base64 Encoded: SGVsbG8gV29ybGQh
Hello World!

base64 Module: Encoding and Decoding Base32

The base64 module also includes encoding and decoding functions for Base32. These functions are very similar to the Base64 functions:

import base64
Creating a string s = "Hello World!"
Encoding the string into bytes b = s.encode("UTF-8")
Base32 Encode the bytes
e = base64.b32encode(b)
Decoding the Base32 bytes to string s1 = e.decode("UTF-8")
Printing Base32 encoded string print("Base32 Encoded:", s1)
Encoding the Base32 encoded string into bytes b1 = s1.encode("UTF-8")
Decoding the Base32 bytes
d = base64.b32decode(b1)
Decoding the bytes to string s2 = d.decode("UTF-8") print(s2)

This would produce the following output:

Base32 Encoded: JBSWY3DPEBLW64TMMQQQ====
Hello World!

Encoding and Decoding Base16

The base64 module also includes encoding and decoding functions for Base16. Base 16 is most commonly referred to as hexadecimal. These functions are very similar to the both the Base64 and Base32 functions:

import base64
Creating a string s = "Hello World!"
Encoding the string into bytes b = s.encode("UTF-8")
Base16 Encode the bytes
e = base64.b16encode(b)
Decoding the Base16 bytes to string s1 = e.decode("UTF-8")
Printing Base16 encoded string print("Base16 Encoded:", s1)
Encoding the Base16 encoded string into bytes b1 = s1.encode("UTF-8")
Decoding the Base16 bytes
d = base64.b16decode(b1)
Decoding the bytes to string s2 = d.decode("UTF-8") print(s2)

This would produce the following output:

Base16 Encoded: 48656C6C6F20576F726C6421
Hello World!

Encoding and Decoding ASCII85

Adobe created its own encoding called ASCII85 which is similar to Base85, but has its differences. This encoding is used frequently in Adobe PDF files. These functions were released in Python version 3.4. Otherwise, the functions base64.a85encode() and base64.a85encode() are similar to the previous:

import base64
Creating a string s = "Hello World!"
Encoding the string into bytes b = s.encode("UTF-8")
ASCII85 Encode the bytes
e = base64.a85encode(b)
Decoding the ASCII85 bytes to string s1 = e.decode("UTF-8")
Printing ASCII85 encoded string print("ASCII85 Encoded:", s1)
Encoding the ASCII85 encoded string into bytes b1 = s1.encode("UTF-8")
Decoding the ASCII85 bytes
d = base64.a85decode(b1)
Decoding the bytes to string s2 = d.decode("UTF-8")
print(s2)

This outputs the following:

ASCII85 Encoded: 87cURD]i,"Ebo80
Hello World!

Encoding and Decoding Base85

Just like the Base64, Base32, and Base16 functions, the Base85 encoding and decoding functions are base64.b85encode() and base64.b85decode():

import base64
Creating a string s = "Hello World!"
Encoding the string into bytes b = s.encode("UTF-8")
Base85 Encode the bytes
e = base64.b85encode(b)
Decoding the Base85 bytes to string s1 = e.decode("UTF-8")
Printing Base85 encoded string print("Base85 Encoded:", s1)
Encoding the Base85 encoded string into bytes b1 = s1.encode("UTF-8")
Decoding the Base85 bytes
d = base64.b85decode(b1)
Decoding the bytes to string s2 = d.decode("UTF-8") print(s2)

which outputs the following:

Base85 Encoded: NM&qnZy;B1a%^NF
Hello World!

Learn more

Must Read Python Interview Questions

200+ Python Tutorials With Coding Examples

Python Language Basics TutorialPython String Representations of Class Instances
Python For Beginners TutorialPython Debugging Tutorial
Python Data Types TutorialReading and Writing CSV File Using Python
Python Indentation TutorialWriting to CSV in Python from String/List
Python Comments and Documentation TutorialPython Dynamic Code Execution Tutorial
Python Date And Time TutorialPython Code Distributing using Pyinstaller
Python Date Formatting TutorialPython Data Visualization Tutorial
Python Enum TutorialPython Interpreter Tutorial
Python Set TutorialPython Args and Kwargs
Python Mathematical Operators TutorialPython Garbage Collection Tutorial
Python Bitwise Operators TutorialPython Pickle Data Serialisation
Python Bolean Operators TutorialPython Binary Data Tutorial
Python Operator Precedance TutorialPython Idioms Tutorial
Python Variable Scope And Binding TutorialPython Data Serialization Tutorial
Python Conditionals TutorialPython Multiprocessing Tutorial
Python Comparisons TutorialPython Multithreading Tutorial
Python Loops TutorialPython Processes and Threads
Python Arrays TutorialPython Concurrency Tutorial
Python Multidimensional Arrays TutorialPython Parallel Computation Tutorial
Python List TutorialPython Sockets Module Tutorial
Python List Comprehensions TutorialPython Websockets Tutorial
Python List Slicing TutorialSockets Encryption Decryption in Python
Python Grouby() TutorialPython Networking Tutorial
Python Linked Lists TutorialPython http Server Tutorial
Linked List Node TutorialPython Flask Tutorial
Python Filter TutorialIntroduction to Rabbitmq using Amqpstorm Python
Python Heapq TutorialPython Descriptor Tutorial
Python Tuple TutorialPython Tempflile Tutorial
Python Basic Input And Output TutorialInput Subset and Output External Data Files using Pandas in Python
Python Files And Folders I/O TutorialUnzipping Files in Python Tutorial
Python os.path TutorialWorking with Zip Archives in Python
Python Iterables And Iterators Tutorialgzip in Python Tutorial
Python Functions TutorialStack in Python Tutorial
Defining Functions With List Arguments In PythonWorking with Global Interpreter Lock (GIL)
Functional Programming In PythonPython Deployment Tutorial
Partial Functions In PythonPython Logging Tutorial
Decorators Function In PythonPython Server Sent Events Tutorial
Python Classes TutorialPython Web Server Gateway Interface (WSGI)
Python Metaclasses TutorialPython Alternatives to Switch Statement
Python String Formatting TutorialPython Packing and Unpacking Tutorial
Python String Methods TutorialAccessing Python Sourcecode and Bytecode
Using Loops Within Functions In PythonPython Mixins Tutorial
Python Importing Modules TutorialPython Attribute Access Tutorial
Difference Betweeb Module And Package In PythonPython Arcpy Tutorial
Python Math Module TutorialPython Abstract Base Class Tutorial
Python Complex Math TutorialPython Plugin and Extension Classes
Python Collections Module TutorialPython Immutable Datatypes Tutorial
Python Operator Module TutorialPython Incompatibilities Moving from Python 2 to Python 3
Python JSON Module TutorialPython 2to3 Tool Tutorial
Python Sqlite3 Module TutorialNon-Official Python implementations
Python os Module TutorialPython Abstract Syntax Tree
Python Locale Module TutorialPython Unicode and Bytes
Python Itertools Module TutorialPython Serial Communication (pyserial)
Python Asyncio Module TutorialNeo4j and Cypher using Py2Neo
Python Random Module TutorialBasic Curses with Python
Python Functools Module TutorialTemplates in Python
Python dis Module TutorialPython Pillow
Python Base64 Module TutorialPython CLI subcommands with precise help output
Python Queue Module TutorialPython Database Access
Python Deque Module TutorialConnecting Python to SQL Server
Python Webbrowser Module TutorialPython and Excel
Python tkinter TutorialPython Turtle Graphics
Python pyautogui Module TutorialPython Persistence
Python Indexing And Slicing TutorialPython Design Patterns
Python Plotting With Matplotlib TutorialPython hashlib
Python Graph Tool TutorialCreating a Windows Service Using Python
Python Generators TutorialMutable vs Immutable (and Hashable) in Python
Python Reduce TutorialPython configparser
Python Map Function TutorialPython Optical Character Recognition
Python Exponentiation TutorialPython Virtual Environments
Python Searching TutorialPython Virtual Environment – virtualenv
Sorting Minimum And Maximum In PythonPython Virtual environment with virtualenvwrapper
Python Print Function TutorialCreate virtual environment with virtualenvwrapper in windows
Python Regular Expressions Regex TutorialPython sys Tutorial
Copying Data In Python TutorialChemPy – Python package
Python Context Managers (“with” Statement) TutorialPython pygame
Python Name Special Variable TutorialPython pyglet
Checking Path Existence And Permissions In PythonWorking with Audio in Python
Creating Python Packages TutorialPython pyaudio
Usage of pip Module In Python TutorialPython shelve
Python PyPi Package Manager TutorialIoT Programming with Python and Raspberry PI
Parsing Command Line Arguments In Pythonkivy – Cross-platform Python Framework for NUI Development
Python Subprocess Library TutorialPandas Transform
Python setup.py TutorialPython vs. JavaScript
Python Recursion TutorialCall Python from C#
Python Type Hints TutorialPython Writing Extensions
Python Exceptions TutorialPython Lex-Yacc
Raise Custom Exceptions In PythonPython Unit Testing
Python Commonwealth Exceptions TutorialPython py.test
Python urllib TutorialPython Profiling
Web Scraping With Python TutorialPython Speed of Program
Python HTML Parsing TutorialPython Performance Optimization
Manipulating XML In PythonPython Security and Cryptography
Python Requests Post TutorialSecure Shell Connection in Python
Python Distribution TutorialPython Anti Patterns
Python Property Objects TutorialPython Common Pitfalls
Python Overloading TutorialPython Hidden Features
Python Polymorphism TutorialPython For Machine Learning
Python Method Overriding TutorialPython Interview Questions And Answers For Experienced
Python User Defined Methods TutorialPython Coding Interview Questions And Answers
Python Programming Tutorials With Examples

Other Python Tutorials

Leave a Comment