Python bytes() Function

Python’s built-in bytes(source) function creates an immutable bytes object initialized as defined in the function argument source. A bytes object is like a string but it uses only byte characters consisting of a sequence of 8-bit integers in the range 0<=x<256. The returned byte object is immutable—you cannot change it after creation. If you plan to change the contents, use the bytearray() method to create a mutable bytearray object.

Here’s a minimal example that creates a byte from three integers stored in a list:

>>> bytes([1, 2, 3])
b'\x01\x02\x03'

The prefix \x escape sequence means the next two characters are interpreted as hex character codes. For instance, the hex code \x01 is the same as chr(0x01)=16*0+1=1 that’s simply a start of heading SOH character. (source, ASCII table)

Syntax: bytes([source[, encoding[, errors]]])
Argumentsource (Optional)Allows you to initialize the byte in four different ways (from simple to more complex):

🐍 integer –> array has this size and is initialized with 0 bytes:
>>> bytes(4)
b'\x00\x00\x00\x00'


🐍 iterable –> integers in the range 0 <= x < 256 are initial byte contents:
>>> bytes([1, 2, 3])
b'\x01\x02\x03'


🐍 string and you provide the encoding (and optionally, errors) arguments –> bytes() converts string to bytes using str.encode():
>>> bytes('hi', 'UTF-8')
b'hi'


🐍 object implementing the buffer interface –> initializes the byte object via a read-only object buffer.
Argumentencoding (Optional)The encoding used in case you provide a string argument. Example: 'UTF-8'.
Argumenterrors (Optional)The action to take when the encoding conversion fails. Only makes sense if source argument is a string.
Return ValuebyteReturns a new object of type byte—a sequence of bytes that is immutable. For a mutable version, consider using the bytearray() function.
⭐ Without an optional argument, it returns a byte object with one byte 0:
>>> bytes()
b''

Here are some basic usages of the function:

Input : bytes(4)
Output : b'\x00\x00\x00\x00'

Input : bytes([1, 2, 3])
Output : b'\x01\x02\x03'

Input : bytes('hi', 'UTF-8')
Output : b'hi'

Want to learn more? We’re going to dive into more examples next!


But before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Link: https://nostarch.com/pythononeliners

Create Bytes Object From Single Integer Argument — Examples

The following code shows you how to use the bytes() function on simple integer arguments.

# Single Integer Input Argument
print(bytes())
print(bytes(2))
print(bytes(4))

'''
b''
b'\x00\x00'
b'\x00\x00\x00\x00'
'''

If you provide only one input argument, it uses this input argument to determine how many bytes should be created. It just uses bytes with value 0, in byte notation x00 to fill the byte.

Create Bytes Object From Iterable of Integers — Examples

You can also provide an iterable argument to obtain a new byte object:

# Iterable Input Argument
print(bytes([1, 1, 1]))
print(bytes([14]))
print(bytes({9, 8, 7}))

'''
b'\x01\x01\x01'
b'\x0e'
b'\x08\t\x07'
'''

The iterable must consist of a number of integers between 0 and 256. If you fail to do so, Python will throw a ValueError:

How to Fix “ValueError: byte must be in range(0, 256)”

If you use the bytes() function on an iterable that contains at least one integer greater than the maximum number representable by 8 bits, namely 256, or smaller than 0, Python will throw a ValueError: byte must be in range(0, 256). You can fix it by ensuring that each number in your iterable can actually be represented by 8 bits and falls into the interval 0 to 256.

Here’s an example of the ValueError where you use a number larger or equal than 256:

>>> bytes([999])
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    bytes([999])
ValueError: bytes must be in range(0, 256)

Another example when using a number smaller than 0:

>>> bytes([-10])
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    bytes([-10])
ValueError: bytes must be in range(0, 256)

Fix it by modifying the numbers to lie within the interval 0 to 256:

>>> bytes([255])
b'\xff'

Summary

Python’s built-in function bytes() allows you to initialize the byte in four different ways (from simple to more complex):

🐍 integer –> array has this size and is initialized with 0 bytes:

>>> bytes(4)
b'\x00\x00\x00\x00'

🐍 iterable –> integers in the range 0 <= x < 256 are initial byte contents:

>>> bytes([1, 2, 3])
b'\x01\x02\x03'

🐍 string and you provide the encoding (and optionally, errors) arguments –> bytes() converts string to bytes using str.encode():

>>> bytes('hi', 'UTF-8')
b'hi'

🐍 object implementing the buffer interface –> initializes the byte object via a read-only object buffer.

Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!