The bytes
class in Python is a built-in type used to represent binary data. bytes
objects are immutable - once created, their elements cannot be modified. Since binary data is typically immutable, the bytes
type is widely used in file operations, network communications, and similar scenarios.
The syntax for the bytes
class is:
bytes([source[, encoding[, errors]]])
Where:
source
: Can be an integer, an iterable containing integers, a string, abytes
object, or a readable objectencoding
: Required ifsource
is a string, specifies character encodingerrors
: Specifies error handling scheme for encoding, defaults to 'strict'
Common bytes Operations
Here are some common operations with bytes
:
len(bytes_object)
: Returns the number of bytes inbytes_object
bytes_object[index]
: Returns the byte atindex
bytes_object.count(sub[, start[, end]])
: Returns count of subsequencesub
bytes_object.find(sub[, start[, end]])
: Finds position of subsequencesub
, returns-1
if not foundbytes_object.hex()
: Returns hexadecimal representation
Example Code
# Create empty bytes object
b = bytes()
# Create bytes objects
b = bytes([97, 98, 99]) # b'abc'
b = bytes('abc', 'ascii') # b'abc'
# Output bytes object
print(b) # b'abc'
print(len(b)) # 3
# Access elements
print(b[1]) # 98
# Find subsequences
print(b.find(b'bc')) # 1
print(b.find(b'def')) # -1
# Convert to hex string
s = b.hex()
print(s) # '616263'
# Convert hex string to bytes
b = bytes.fromhex('68656c6c6f')
print(b) # b'hello'
Note that in Python 3, strings use Unicode
encoding, so when working with binary data you should use either bytes
or bytearray
types. To convert binary data to a string, use the bytes.decode()
method with the appropriate character encoding. For example, b.decode('ascii')
decodes the byte string to an ASCII
-encoded string.