Bytes
In Python, a bytes object is an immutable sequence of integers in the range 0 <= x < 256. It represents raw binary data. Bytes are essential for handling binary data, such as network communication, file I/O, and image processing.
Creating Bytes Objects
There are several ways to create bytes objects:
1. Using the bytes() constructor:
o From a string:
Python
text = "Hello"
byte_data = bytes(text, encoding='utf-8')
print(byte_data) # Output: b'Hello'
o From an iterable of integers:
Python
byte_data = bytes([65, 66, 67])
print(byte_data) # Output: b'ABC'
o From a given size:
Python
byte_data = bytes(5)
print(byte_data) # Output: b'\x00\x00\x00\x00\x00'
2. Using a byte literal:
Python
byte_data = b'Hello'
print(byte_data) # Output: b'Hello'
Accessing Bytes
You can access individual bytes using indexing:
Python
byte_data = b'Hello'
first_byte = byte_data[0] # Output: 72
Immutability
Bytes objects are immutable, meaning you cannot modify their contents after creation.
Common Operations
- Slicing: Extract a portion of the bytes object.
- Concatenation: Combine two bytes objects using the + operator.
- Membership testing: Check if a byte value is present using the in keyword.
- Length: Get the number of bytes using len().
Example
Python
byte_data = b'Hello, world!'
# Slicing
first_five_bytes = byte_data[:5]
print(first_five_bytes) # Output: b'Hello'
# Concatenation
new_data = byte_data + b' How are you?'
print(new_data) # Output: b'Hello, world! How are you?'
# Membership testing
if 72 in byte_data:
print("H is present")
Key Points
- Bytes objects represent raw binary data.
- They are immutable.
- Used for handling binary data, network communication, and file I/O.
- Can be created from strings, integers, or other byte-like objects.