base64 encoding takes 8-bit binary byte data and encodes it uses only the characters A-Z, a-z, 0-9, +, /* so it can be transmitted over channels that do not preserve all 8-bits of data, such as email.

Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the b'' syntax.

If you remove the b, it becomes a string. A string is a sequence of Unicode characters. base64 has no idea what to do with Unicode data, it's not 8-bit. It's not really any bits, in fact. :-)

In your second example:

>>> encoded = base64.b64encode('data to be encoded')

All the characters fit neatly into the ASCII character set, and base64 encoding is therefore actually a bit pointless. You can convert it to ascii instead, with

>>> encoded = 'data to be encoded'.encode('ascii')

Or simpler:

>>> encoded = b'data to be encoded'

Which would be the same thing in this case.


* Most base64 flavours may also include a = at the end as padding. In addition, some base64 variants may use characters other than + and /. See the Variants summary table at Wikipedia for an overview.

Answer from Lennart Regebro on Stack Overflow
🌐
Python
docs.python.org › 3 › library › base64.html
base64 — Base16, Base32, Base64, Base85 Data Encodings
This module provides functions for encoding binary data to printable ASCII characters and decoding such encodings back to binary data. This includes the encodings specified in RFC 4648 (Base64, Base32 and Base16), the Base85 encoding specified ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › encoding-and-decoding-base64-strings-in-python
Encoding and Decoding Base64 Strings in Python - GeeksforGeeks
August 7, 2024 - The below image provides us with a Base64 encoding table. ... In Python the base64 module is used to encode and decode data. First, the strings are converted into byte-like objects and then encoded using the base64 module.
Top answer
1 of 5
363

base64 encoding takes 8-bit binary byte data and encodes it uses only the characters A-Z, a-z, 0-9, +, /* so it can be transmitted over channels that do not preserve all 8-bits of data, such as email.

Hence, it wants a string of 8-bit bytes. You create those in Python 3 with the b'' syntax.

If you remove the b, it becomes a string. A string is a sequence of Unicode characters. base64 has no idea what to do with Unicode data, it's not 8-bit. It's not really any bits, in fact. :-)

In your second example:

>>> encoded = base64.b64encode('data to be encoded')

All the characters fit neatly into the ASCII character set, and base64 encoding is therefore actually a bit pointless. You can convert it to ascii instead, with

>>> encoded = 'data to be encoded'.encode('ascii')

Or simpler:

>>> encoded = b'data to be encoded'

Which would be the same thing in this case.


* Most base64 flavours may also include a = at the end as padding. In addition, some base64 variants may use characters other than + and /. See the Variants summary table at Wikipedia for an overview.

2 of 5
252

Short Answer

You need to push a bytes-like object (bytes, bytearray, etc) to the base64.b64encode() method. Here are two ways:

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

Or with a variable:

>>> import base64
>>> string = 'data to be encoded'
>>> data = base64.b64encode(string.encode())
>>> print(data)
b'ZGF0YSB0byBiZSBlbmNvZGVk'

Why?

In Python 3, str objects are not C-style character arrays (so they are not byte arrays), but rather, they are data structures that do not have any inherent encoding. You can encode that string (or interpret it) in a variety of ways. The most common (and default in Python 3) is utf-8, especially since it is backwards compatible with ASCII (although, as are most widely-used encodings). That is what is happening when you take a string and call the .encode() method on it: Python is interpreting the string in utf-8 (the default encoding) and providing you the array of bytes that it corresponds to.

Base-64 Encoding in Python 3

Originally the question title asked about Base-64 encoding. Read on for Base-64 stuff.

base64 encoding takes 6-bit binary chunks and encodes them using the characters A-Z, a-z, 0-9, '+', '/', and '=' (some encodings use different characters in place of '+' and '/'). This is a character encoding that is based off of the mathematical construct of radix-64 or base-64 number system, but they are very different. Base-64 in math is a number system like binary or decimal, and you do this change of radix on the entire number, or (if the radix you're converting from is a power of 2 less than 64) in chunks from right to left.

In base64 encoding, the translation is done from left to right; those first 64 characters are why it is called base64 encoding. The 65th '=' symbol is used for padding, since the encoding pulls 6-bit chunks but the data it is usually meant to encode are 8-bit bytes, so sometimes there are only two or 4 bits in the last chunk.

Example:

>>> data = b'test'
>>> for byte in data:
...     print(format(byte, '08b'), end=" ")
...
01110100 01100101 01110011 01110100
>>>

If you interpret that binary data as a single integer, then this is how you would convert it to base-10 and base-64 (table for base-64):

base-2:  01 110100 011001 010111 001101 110100 (base-64 grouping shown)
base-10:                            1952805748
base-64:  B      0      Z      X      N      0

base64 encoding, however, will re-group this data thusly:

base-2:  011101  000110  010101 110011 011101 00(0000) <- pad w/zeros to make a clean 6-bit chunk
base-10:     29       6      21     51     29      0
base-64:      d       G       V      z      d      A

So, 'B0ZXN0' is the base-64 version of our binary, mathematically speaking. However, base64 encoding has to do the encoding in the opposite direction (so the raw data is converted to 'dGVzdA') and also has a rule to tell other applications how much space is left off at the end. This is done by padding the end with '=' symbols. So, the base64 encoding of this data is 'dGVzdA==', with two '=' symbols to signify two pairs of bits will need to be removed from the end when this data gets decoded to make it match the original data.

Let's test this to see if I am being dishonest:

>>> encoded = base64.b64encode(data)
>>> print(encoded)
b'dGVzdA=='

Why use base64 encoding?

Let's say I have to send some data to someone via email, like this data:

>>> data = b'\x04\x6d\x73\x67\x08\x08\x08\x20\x20\x20'
>>> print(data.decode())
   
>>> print(data)
b'\x04msg\x08\x08\x08   '
>>>

There are two problems I planted:

  1. If I tried to send that email in Unix, the email would send as soon as the \x04 character was read, because that is ASCII for END-OF-TRANSMISSION (Ctrl-D), so the remaining data would be left out of the transmission.
  2. Also, while Python is smart enough to escape all of my evil control characters when I print the data directly, when that string is decoded as ASCII, you can see that the 'msg' is not there. That is because I used three BACKSPACE characters and three SPACE characters to erase the 'msg'. Thus, even if I didn't have the EOF character there the end user wouldn't be able to translate from the text on screen to the real, raw data.

This is just a demo to show you how hard it can be to simply send raw data. Encoding the data into base64 format gives you the exact same data but in a format that ensures it is safe for sending over electronic media such as email.

🌐
Stack Abuse
stackabuse.com › encoding-and-decoding-base64-strings-in-python
Encoding and Decoding Base64 Strings in Python
September 4, 2023 - Without using 'rb', Python would assume we are reading a text file. We then use the read() method to get all the data in the file into the binary_file_data variable. Similar to how we treated strings, we Base64 encoded the bytes with base64.b64encode and then used the decode('utf-8') on base64_encoded_data to get the Base64 encoded data using human-readable characters.
🌐
iO Flood
ioflood.com › blog › python-base64-encode
Python Base64 Encode | b64encode() Function Guide
February 1, 2024 - The b64encode() function is suitable for general purpose base64 encoding, while urlsafe_b64encode() is ideal when you need to include the encoded data in a URL. In conclusion, Python’s base64 module offers a variety of methods for base64 encoding to cater to different needs.
🌐
Medium
medium.com › @ume.cooray › understanding-base64-encoding-in-python-5b31f23dd007
Understanding Base64 Encoding and Decoding in Python | by Umayangana Cooray | Medium
March 18, 2025 - import base64 import json # Example JSON token (as a string) json_token = "" # Step 1: Convert the JSON string to bytes json_bytes = json_token.encode('utf-8') # Step 2: Encode the bytes using Base64 base64_bytes = base64.b64encode(json_bytes) # Step 3: Convert the encoded bytes back to a string (optional) base64_string = base64_bytes.decode('utf-8') print("Base64 Encoded String:", base64_string) ... In Python, strings need to be converted to bytes before encoding.
🌐
Base64Encode.org
base64encode.org › enc › python
Base64 Encoding of "python" - Online
Encode python to Base64 format with various advanced options. Our site has an easy to use online tool to convert your data.
🌐
GitHub
github.com › mayeut › pybase64
GitHub - mayeut/pybase64: Fast Base64 encoding/decoding in Python · GitHub
May 16, 2026 - Running Python 3.15.0b4, Apple clang version 21.0.0 (clang-2100.1.1.101), macOS 26.5.2, Apple M1 Max · pybase64 1.5.0 (C extension active - NEON) bench: altchars=None, validate=True, padded=True pybase64.encodebytes: 6632 MB/s (135,696 bytes -> 183,309 bytes) pybase64.b64encode: 17672 MB/s (135,696 bytes -> 180,928 bytes) pybase64.b64decode: 9058 MB/s (180,928 bytes -> 135,696 bytes) base64.encodebytes: 2383 MB/s (135,696 bytes -> 183,309 bytes) base64.b64encode: 2665 MB/s (135,696 bytes -> 180,928 bytes) base64.b64decode: 2631 MB/s (180,928 bytes -> 135,696 bytes) bench: altchars=None, valid
Starred by 181 users
Forked by 20 users
Languages   Python 63.6% | C 36.4%
Find elsewhere
🌐
Base64.Guru
base64.guru › home › developers › python
Python Base64 Encode | Python | Developers | Base64
data (required string) - Text or binary content that you want to encode · altchars (optional string; default None) - Two characters that should replace “+” and “/” · str - On success, it returns the Base64 value, typically longer by about 33% than data ... from base64 import b64encode data = 'guru' print(b64encode(data)) #-> 'Z3VydQ==' SyntaxError: bytes can only contain ASCII literal characters. Example #2 (fix the “TypeError: a bytes-like object is required, not 'str'” error on Python 3):
🌐
W3Schools
w3schools.com › python › ref_module_base64.asp
Python base64 Module
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... import base64 s = "Linus".encode() b = base64.b64encode(s) print(b) print(base64.b64decode(b).decode()) Try it Yourself »
🌐
Real Python
realpython.com › ref › stdlib › base64
base64 | Python Standard Library – Real Python
Encoding and decoding with the standard Base64 alphabet: ... >>> import base64 >>> base64.b64encode(b"Python is great") b'UHl0aG9uIGlzIGdyZWF0' >>> base64.b64decode(b"UHl0aG9uIGlzIGdyZWF0") b'Python is great'
🌐
Python Module of the Week
pymotw.com › 2 › base64
base64 – Encode binary data into ASCII characters - Python Module of the Week
import base64 original_string = ...ded_string) print 'Decoded :', decoded_string · The encoding process looks at each sequence of 24 bits in the input (3 bytes) and encodes those same 24 bits spread over 4 bytes in the output....
🌐
Educative
educative.io › answers › how-to-use-base64b64encode-in-python
How to use base64.b64encode() in Python
The base64.b64encode() function takes s as a non-optional parameter and altchars as an optional parameter. s contains a byte-like object that is to be encoded.
🌐
DEV Community
dev.to › tooleroid › base64-encoding-in-python-simplified-guide-examples-nan
Base64 Encoding in Python: Simplified Guide & Examples - DEV Community
December 16, 2024 - Encode files like images and videos for APIs. Safeguard binary data in text-based formats like JSON or XML. Decode received Base64 strings back into usable binary data. Python’s base64 module includes b64encode for encoding text or binary data.
🌐
Envato Tuts+
code.tutsplus.com › home › coding fundamentals › oop
Base64 Encoding and Decoding Using Python | Envato Tuts+
April 11, 2022 - The first thing we have to do in order to use Base64 in Python is to import the base64 module: ... In order to encode the image, we simply use the function base64.b64encode(s).
🌐
Base64 Encode
base64encode.net › python-base64-b64encode
Python base64.b64encode() - Base64 Encode
<<< import base64 <<< encoded = base64.b64encode('base64 encoded string') <<< encoded 'YmFzZTY0IGVuY29kZWQgc3RyaW5n'
🌐
TutorialsPoint
tutorialspoint.com › cryptography_with_python › cryptography_with_python_base64_encoding_and_decoding.htm
Base64 Encoding and Decoding
Python includes a module called ... as an object. Base64.encode(input, output) − It encodes the input value parameter specified and stores the decoded output as an object....
🌐
AskPython
askpython.com › python › examples › decoding-base64-data
Decoding Base64 Data in Python - AskPython
April 29, 2026 - Base64 is an encoding scheme that converts binary data into ASCII text. It does this by mapping each 6 bits of input to one of 64 characters: uppercase A-Z, lowercase a-z, digits 0-9, plus (+), and forward slash (/). The equals sign (=) is used ...
🌐
Cybrosys Technologies
cybrosys.com › odoo blogs
Base64 Encoding & Decoding Using Python
July 18, 2023 - The Python base64 module provides an easy way to encrypt and decrypt binary data using the Base64 encoding technique. It is also extremely simple to use.