Python bytes()
: Immutable Sequence of Bytes
The bytes()
function in Python creates an immutable sequence of bytes. It’s widely used for binary data handling, network communication, file I/O, and encryption.
Why Use bytes()
?
Unlike bytearray()
, which is mutable, bytes()
objects cannot be changed after creation. This makes them faster and more memory-efficient, especially when working with large binary data that doesn’t need modification.
Syntax
bytes(source, encoding, errors)
- source → Initial data (string, list, or integer).
- encoding (optional) → Required when converting a string.
- errors (optional) → Specifies error handling for encoding.
If no argument is passed, it creates an empty bytes()
object (b''
).
1. Converting a String to bytes()
Common in file operations, APIs, and networking, where data needs to be sent as bytes.
data = bytes("Hello", "utf-8")
print(data) # Output: b'Hello'
You can’t modify bytes()
, but you can decode it back to a string:
print(data.decode()) # Output: Hello
This is useful when handling encoded text in APIs or databases.
2. Creating bytes()
from a List of Integers
Each number represents a byte (0-255), useful for binary data processing like images or encryption.
binary_data = bytes([65, 66, 67])
print(binary_data) # Output: b'ABC'
This is helpful in low-level file formats, networking, and cryptography.
3. Using bytes()
for Fixed-Length Binary Data
If you need a fixed-length binary object (e.g., zero-filled memory for encryption), use:
empty_bytes = bytes(5) # Creates b'\x00\x00\x00\x00\x00'
This is often used in buffer allocation and low-level system programming.
4. SQL Use Case: Storing Binary Data
Databases often store images, files, or encrypted data as BLOBs
(Binary Large Objects).
user_avatar = bytes("image_binary_data", "utf-8")
print(f"INSERT INTO users (profile_picture) VALUES ({user_avatar});")
This ensures efficient storage and retrieval of binary content.
Key Notes
- ✔ Immutable, unlike
bytearray()
– great for security & efficiency. - ✔ Ideal for handling binary files, encryption, and networking.
- ✔ Memory-efficient – prevents accidental modification.
- ✔ Works well with databases & APIs – ensures proper encoding of binary data.
By using bytes()
, you can handle binary data safely and efficiently, whether for network protocols, encryption, or file storage. 🚀