Remember
bytes() creates an immutable sequence of bytes. Encoding text requires an explicit encoding.
bytes() creates an immutable sequence of bytes. Encoding text requires an explicit encoding.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
text = 'tea'
data = bytes(text, "utf-8")
print(data)Top-level scope
'tea'Object 2 · bytesb'tea'bytes() creates an immutable sequence of bytes. Encoding text requires an explicit encoding.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
text = 'tea'
data = bytes(text, "utf-8")
print(data)
|
v
DISPLAYED RESULT
b'tea'
FINAL BINDINGS
text --> object 1 (str)
data --> object 2 (bytes)
object 1: 'tea'
object 2: b'tea'Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
text = 'tea'
data = bytes(text, "utf-8")
print(data)Top-level scope
'tea'Object 2 · bytesb'tea'The example has finished. Compare the final output with the values and references above.
b'tea'
What do you expect this program to print?
text = 'tea'
data = bytes(text, "utf-8")
print(data)bytes() FunctionThe bytes() function in Python is used to create an immutable sequence of bytes. It is commonly used when working with binary data, such as reading from or writing to files, networking, or handling encoded data.
bytes([source[, encoding[, errors]]])
source (optional) – Data to convert into bytes (e.g., string, iterable, or integer).encoding (optional) – Encoding to use when the source is a string.errors (optional) – Specifies how to handle encoding errors (e.g., 'strict', 'ignore').empty = bytes()
print(empty)
b''
text = "hello"
b = bytes(text, encoding="utf-8")
print(b)
b'hello'
data = [65, 66, 67]
b = bytes(data)
print(b)
b'ABC'
b = bytes(4)
print(b)
b'\x00\x00\x00\x00'
This creates a bytes object of size 4 with each byte set to 0.
encoding when converting a stringbytearray() for mutable sequences)The bytes() function is often useful in interviews involving file I/O, sockets, or data serialization. Remember that it's immutable!
bytes() creates immutable sequences of bytesbytearray()Ask the user to input a string, convert it to bytes, and print the result.
user_input = input("Enter a message: ")
b = bytes(user_input, encoding="utf-8")
print("Byte version:", b)
Connect what you noticed in the example with the idea below.
bytes() creates an immutable sequence of bytes. Encoding text requires an explicit encoding.
You can assign a new value to an element of a bytes object.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.