You can use bytearray for exactly this. Possibly the binascii module and struct can be helpful, too.

import binascii
import struct

binstr=b"thisisunreadablebytes"

encoded=binascii.b2a_base64(binstr)
print encoded
print binascii.a2b_base64(encoded)

ba=bytearray(binstr)
print list(ba)

print binascii.b2a_hex(binstr)
print struct.unpack("21B",binstr)
Answer from janbrohl on Stack Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ why does base64.b64encode() in python3 return a bytes object, not a string object? isn't converting to string the point?
r/learnpython on Reddit: Why does base64.b64encode() in python3 return a bytes object, not a string object? Isn't converting to string the point?
July 29, 2017 -

The question is pretty much in the title. I was working on porting some code to Python3 that talks to an old API at work - there is a bunch of base64 encoding and hmac creation, which when going from Python 2 to 3 means being explicit about what is a string and what is a byte array. But the b64encode returning a byte array tripped me up, because it doesn't make sense (unless I'm missing something).

Shouldn't b64encode take bytes and return string, and b64decode take string and return bytes?

Discussions

How to convert from Base64 to string Python 3.2 - Stack Overflow
You will see that base64 has two very handy functions, namely b64decode and b64encode. b64 decode returns a byte array and b64encode requires a bytes array. To convert a string into it's base64 representation you first need to convert it to bytes. More on stackoverflow.com
๐ŸŒ stackoverflow.com
March 19, 2021
Convert byte[] to base64 and ASCII in Python - Stack Overflow
How do I to convert and array of byte to base64 string and/or ASCII. I can do this easily in C#, but can't seem to do this in Python More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 20, 2020
python - Why do I need 'b' to encode a string with Base64? - Stack Overflow
CopyTraceback (most recent call ... "/usr/local/lib/python3.12/base64.py", line 58, in b64encode encoded = binascii.b2a_base64(s, newline=False) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: a bytes-like object is required, not 'str' ... Actually all questions that return "TypeError: expected bytes, not str" have the same answer. ... That b simply means you are taking input as a bytes or bytes array not as a string... More on stackoverflow.com
๐ŸŒ stackoverflow.com
March 1, 2017
Python Get Base64 Encoded Byte String as a String of Bytes - Stack Overflow
Given the python code import base64 byte = base64.b64encode(b'hello') byte has the value b'aGVsbG8=' But I'm trying to get the string of the literal encoded bytes inside the b'...' notation. Only More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
pythontutorials
pythontutorials.net โ€บ blog โ€บ decode-base64-string-to-byte-array
How to Decode Base64 String to Byte Array in Python 2.7 for Embedded Microcontroller Projects โ€” pythontutorials.net
Python 2.7 includes a built-in base64 module for Base64 operations. Key details for decoding: The base64.b64decode(s) function decodes a Base64 string s into a byte array.
๐ŸŒ
Rip Tutorial
riptutorial.com โ€บ encoding and decoding base64
Python Language Tutorial => Encoding and Decoding Base64
# 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)
Find elsewhere
๐ŸŒ
Python
docs.python.org โ€บ 3.1 โ€บ library โ€บ base64.html
18.6. base64 โ€” RFC 3548: Base16, Base32, Base64 Data Encodings โ€” Python v3.1.5 documentation
Encode the contents of the binary input file and write the resulting base64 encoded data to the output file. input and output must be file objects. input will be read until input.read() returns an empty bytes object. encode() returns the encoded data plus a trailing newline character (b'\n'). ...
๐ŸŒ
Codetinkering
codetinkering.com โ€บ python-base64-strings-bytes
Base64 shenanigans in Python โ€“ Code Tinkering
November 30, 2022 - import base64 # This is the string you want to decode my_string = 'SGVsbG8gV29ybGQ=' # First, transform the string into its respective bytes my_bytes = my_string.encode('utf-8') # Next, use the base64 decode method to decode the bytes to base64 base64_bytes = base64.b64decode(my_bytes) # Finally, ...
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ encoding-and-decoding-base64-strings-in-python
Encoding and Decoding Base64 Strings in Python
September 4, 2023 - Python 3 provides a base64 module that allows us to easily encode and decode information. We first convert the string into a bytes-like object.
๐ŸŒ
Byteary
byteary.com โ€บ free tools โ€บ byte array tools โ€บ byte array to base64 converter
Byte Array to Base64 Converter - and Base64 to Bytes | Byteary
Convert a byte array to Base64 or Base64 back to a byte array. Supports URL-safe Base64, decimal and hex output, and arrays for Java, Python, C and JS.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ base64.html
base64 โ€” Base16, Base32, Base64, Base85 Data Encodings
This includes the encodings specified in RFC 4648 (Base64, Base32 and Base16), the Base85 encoding specified in PDF 2.0, and non-standard variants of Base85 used elsewhere. There are two interfaces provided by this module. The modern interface supports encoding bytes-like objects to ASCII bytes, and decoding bytes-like objects or strings containing ASCII to bytes.
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.

๐ŸŒ
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 - Letโ€™s walk through the following ... bytes json_bytes = json_token.encode('utf-8') # Step 2: Encode the bytes using Base64 base64_bytes = ......
๐ŸŒ
Python Guides
pythonguides.com โ€บ python-string-to-byte-array
Convert a String to a Byte Array in Python
September 23, 2025 - Learn three easy methods to convert a string to a byte array in Python using bytes(), bytearray(), and encode(). Includes examples and best practices.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ encoding-and-decoding-base64-strings-in-python
Encoding and Decoding Base64 Strings in Python - GeeksforGeeks
August 7, 2024 - 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.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-use-base64b64decode-in-python
How to use base64.b64decode() in Python
The base64.b4() function in Python decodes strings or byte-like objects encoded in base64 and returns the decoded bytes.
๐ŸŒ
Nim Forum
forum.nim-lang.org โ€บ t โ€บ 7359
Base64-decoding binary data to byte array
January 3, 2021 - Sign up ยท Log in ยท Reset your password ยท Create account ยท Reset password ยท Create a new account
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-use-base64b64encode-in-python
How to use base64.b64encode() in Python
The base64.b64() function in Python encodes byte-like objects and returns the encoded bytes.