-
Hajipur, Bihar, 844101
In Python, bytes and bytearray are data types used to handle binary data. They are especially useful when working with files, network communications, or low-level data processing. While strings represent text data, bytes and bytearrays allow you to manipulate raw binary sequences efficiently.
This tutorial will cover the differences between bytes and bytearrays, how to create and manipulate them, and practical examples for real-world applications.
A bytes object is an immutable sequence of integers in the range 0–255. Each element in a bytes object represents a byte of data. Since bytes are immutable, you cannot modify them after creation.
Example:
data = b'Hello'
print(data) # Output: b'Hello'
print(type(data)) # Output: <class 'bytes'>
Here:
The prefix b indicates that it is a bytes literal.
Each character in the string 'Hello' is converted into a byte using ASCII encoding.
A bytearray is similar to bytes but mutable, which means you can modify its elements after creation. Bytearrays are useful when you need to manipulate binary data dynamically.
Example:
data_array = bytearray(b'Hello')
print(data_array) # Output: bytearray(b'Hello')
data_array[0] = 72 # ASCII for 'H' is 72
print(data_array) # Output: bytearray(b'Hello')
Here, you can see that elements can be changed, unlike bytes, making bytearrays more flexible for certain operations.
b1 = b'Python'
ba1 = bytearray(b'Python')
b2 = bytes([65, 66, 67]) # Output: b'ABC'
ba2 = bytearray([65, 66, 67]) # Output: bytearray(b'ABC')
text = "Hello"
b3 = bytes(text, 'utf-8')
ba3 = bytearray(text, 'utf-8')
Here, encoding converts a string into bytes or bytearray using a specific character encoding, such as utf-8 or ascii.
Bytes and bytearrays support indexing and slicing like lists or strings:
data = b'Python'
print(data[0]) # Output: 80 (ASCII of 'P')
print(data[1:4]) # Output: b'yt'
For bytearrays:
ba = bytearray(b'Python')
print(ba[0]) # Output: 80
ba[0] = 112 # Change 'P' to 'p'
print(ba) # Output: bytearray(b'python')
b = b'Python'
ba = bytearray(b)
print(len(b)) # Output: 6
print(len(ba)) # Output: 6
for byte in b:
print(byte) # Prints ASCII values
b1 = b'Hello'
b2 = b'World'
b3 = b1 + b2
print(b3) # Output: b'HelloWorld'
For bytearrays:
ba1 = bytearray(b'Hello')
ba2 = bytearray(b'World')
ba1.extend(ba2)
print(ba1) # Output: bytearray(b'HelloWorld')
b = b'Hi' * 3
print(b) # Output: b'HiHiHi'
Bytes to String:
b = b'Hello'
s = b.decode('utf-8')
print(s) # Output: Hello
String to Bytes:
s = "Hello"
b = s.encode('utf-8')
print(b) # Output: b'Hello'
Bytearray to Bytes:
ba = bytearray(b'Hello')
b = bytes(ba)
Bytes to Bytearray:
b = b'Hello'
ba = bytearray(b)
These conversions are important when interacting with files or network sockets, as many APIs require bytes instead of strings.
b.upper(), b.lower()
b.startswith(), b.endswith()
b.find(), b.replace()
b.split()
Bytearrays support all the methods of bytes plus modification methods:
ba.append(x) – adds a byte at the end
ba.extend([x, y]) – adds multiple bytes
ba.insert(i, x) – inserts a byte at index i
ba.pop(i) – removes and returns a byte at index i
ba.remove(x) – removes the first occurrence of a byte
Reading a Binary File:
with open("example.bin", "rb") as file:
data = file.read()
Writing Bytes to a File:
with open("output.bin", "wb") as file:
file.write(b'Hello Bytes')
Converting String to Bytearray and Modifying:
ba = bytearray("Hello", "utf-8")
ba[0] = 104 # Change 'H' to 'h'
print(ba) # Output: bytearray(b'hello')
Concatenating Bytes:
b1 = b'Python '
b2 = b'Bytes'
b3 = b1 + b2
print(b3) # Output: b'Python Bytes'
Network Data Example:
data = b'\x48\x65\x6c\x6c\x6f'
print(data.decode('utf-8')) # Output: Hello
| Feature | Bytes | Bytearray |
|---|---|---|
| Mutability | Immutable | Mutable |
| Memory Efficiency | Slightly higher | Slightly lower |
| Modification | Cannot modify | Can modify elements |
| Use Case | Fixed binary data | Dynamic binary data |
Bytes and bytearrays are essential Python types for handling binary data efficiently. Bytes are immutable, ideal for read-only data or transmission, while bytearrays are mutable, allowing modifications. These data types are widely used in file handling, network communications, cryptography, and low-level data processing. Understanding how to create, manipulate, and convert between bytes, bytearrays, and strings is a key skill for working with Python in real-world applications.
Mastering bytes and bytearrays opens the door to efficient binary data processing and is a foundation for advanced programming tasks in networking and file management.
Create a bytes object containing the text "Python" and print it.
Convert the string "Hello World" into bytes using UTF-8 encoding.
Create a bytearray from the bytes object b'Python' and print it.
Modify the first element of a bytearray b'Python' to change 'P' to 'p'.
Append a new byte representing '!' to a bytearray.
Concatenate two bytes objects: b'Hello ' and b'World'.
Slice the bytes object b'PythonBytes' to get b'Bytes'.
Convert a bytearray back into a string using UTF-8 decoding.
Use the replace() method on a bytes object to replace b'Py' with b'Hi'.
Read the first 10 bytes from a binary file and print them as a bytearray.