-
Hajipur, Bihar, 844101
In Python, bytes
and bytearray
are used to handle binary data.
They look like lists of integers but represent data in bytes form (0 to 255).
data = bytes([65, 66, 67])
print(data) # b'ABC'
print(data[0]) # 65
✅ You cannot change values in a bytes
object.
data = bytearray([65, 66, 67])
print(data) # bytearray(b'ABC')
data[1] = 90
print(data) # bytearray(b'AZC')
✅ You can change values in a bytearray
.
text = "hello"
b = bytes(text, 'utf-8')
print(b) # b'hello'
b = b'hello'
text = b.decode('utf-8')
print(text) # hello
b = b"data"
ba = bytearray(b)
Method | Works On | Description |
---|---|---|
.decode() |
bytes | Converts to string |
.append(x) |
bytearray | Adds one byte to the end |
.pop() |
bytearray | Removes the last byte |
.reverse() |
bytearray | Reverses byte order |
.extend([]) |
bytearray | Adds multiple bytes |
with open("file.bin", "rb") as f:
content = f.read()
print(content) # bytes
Convert string to bytes
Modify bytearray data
Decode bytes into text
Use .append()
or .reverse()
on bytearray
Q1. Write a Python program to create a bytes object with values [65, 66, 67]
and print it.
Q2. Write a Python program to print the second byte from a bytes object.
Q3. Write a Python program to try changing a byte in a bytes object and observe the error (bytes are immutable).
Q4. Write a Python program to create a bytearray and modify the first element.
Q5. Write a Python program to convert the string "Python"
into bytes using UTF-8 encoding.
Q6. Write a Python program to decode b'Hello'
into a string using .decode()
.
Q7. Write a Python program to append the value 88
to a bytearray using append()
.
Q8. Write a Python program to use .reverse()
on a bytearray and print the result.
Q9. Write a Python program to convert a bytes object to a bytearray and modify its content.
Q10. Write a Python program to read a binary file and print its content in bytes.
Q1: What is the data type of b"hello"?
Q2: What value range can bytes hold?
Q3: What is the main difference between bytes and bytearray?
Q4: What will b"data"[0] return?
Q5: Which method converts a bytes object to string?
Q6: Can you change a value in a bytes object?
Q7: Which method adds a new byte to a bytearray?
Q8: What does bytearray(b'data') return?
Q9: What does reverse() do in bytearray?
Q10: What encoding is commonly used with bytes() and .decode()?