In Python, a bytes object is a sequence of bytes. It is immutable and can contain any binary data. Sometimes, it is necessary to get the length of a bytes object for various purposes. In this guide, we will discuss how to get the length of a bytes object in Python.
Using the len() function
The len() function is a built-in function in Python that returns the number of elements in an object. We can use the len() function to get the length of a bytes object as shown below:
my_bytes = b"Hello, World!"
length = len(my_bytes)
print(length) # Output: 13
In the above code, we create a bytes object `my_bytes` that contains the string “Hello, World!”. We then use the len() function to get the length of `my_bytes` and store it in the variable `length`. Finally, we print the value of `length` which is 13.
Conclusion
Getting the length of a bytes object in Python is easy using the len() function. It is a simple and straightforward way to obtain the size of a bytes object.