- author: Python and Pandas with Reuven Lerner
Understanding Bytes in Python: Exploring Built-in Type in Standard Library
Have you ever encountered binary data or had to manipulate binary data? If yes, then you must have heard of bytes, a built-in type in Python. Every piece of information is represented using bytes, in the end. However, we also have characters, which raises a couple of questions. What is the relationship between bytes and characters? How is a string represented in bytes? In this article, we will answer these questions and more as we explore bytes in Python.
What Are Bytes?
Bytes is a built-in type in Python, which means we don’t need any external library to use it. It is meant to handle binary data as opposed to characters and strings.
Creating a Bytes
We can create bytes by specifying a string and the encoding we want to use, like this:
As seen in the example, the "utf-8" is an encoding type that translates the characters (ABCD) to bytes. It is important to note that the bytes object is immutable. Therefore, it cannot be changed once created.
Understanding Bytes as Integers
The way Python represents the bytes is different from strings or characters. While strings or characters are represented as Unicode strings, bytes are represented as integers between 0 and 255.
x returns the first byte as an integer. It is important to note that Python will not return a string representation of the byte, but rather an integer representation.
Hexadecimal Representation of Bytes
If we want to view bytes as hexadecimal digits, we can use the
.hex() method like this:
The output will be a string representation of the bytes in hexadecimal form.
Converting From Hexadecimal to Bytes
We can convert bytes in hexadecimal form to bytes by using the
bytes.fromhex() method, like this:
s="97 98 99"b=bytes.fromhex(s)
Searching for Bytes
We can search for a byte or an integer inside a bytes object.
ginx# Does g exist in bytes x?chr(100)inx# Are there any bytes that represent the character 'd'?
It is important to note that strings cannot be searched for inside bytes.
The bytes type in Python provides an efficient way of representing binary data. It is important to keep in mind the encoding when working with bytes. Bytes are not mutable, so we have to create a new bytes object if we want to make changes. Finally, bytes can be searched for integer values, however, not for strings. Keep these concepts in mind, and you can handle bytes like a pro!