A developer is building an IoT application that reads temperature data from a sensor over a TCP socket. The sensor sends data as a stream of bytes encoded in UTF-8, with each reading terminated by a newline character. The developer uses the following code to receive data: ```python import socket s = socket.socket() s.connect(('sensor.local', 5000)) data = s.recv(1024) ``` The variable `data` is a bytes object. The developer needs to convert it to a string to parse the temperature value. Which of the following lines of code should the developer use to correctly obtain the string representation of the received data, assuming the data is valid UTF-8 and may contain non-ASCII characters?
Because data was read as raw bytes from the IoT sensor, decode('utf-8') is the correct method to interpret those bytes as a Unicode string using the UTF-8 codec. This is the inverse of str.encode() and is exactly what bytes objects are designed to do. After decoding, the result is a normal str that can be compared, parsed, or logged as text.
Why this answer
The `recv()` method returns a bytes object. Since the data is valid UTF-8 and may contain non-ASCII characters, the correct way to convert bytes to a string is by calling `data.decode('utf-8')`. This method interprets the byte sequence according to the UTF-8 encoding and returns a Unicode string.
Exam trap
The trap here is confusing `encode()` and `decode()`: candidates often think bytes need to be 'encoded' to a string, but in Python, bytes are decoded to str, and str is encoded to bytes.
How to eliminate wrong answers
Option A is wrong because `data.encode('utf-8')` attempts to encode a bytes object, which raises an `AttributeError` (bytes have no `encode` method); encoding is for strings, not bytes. Option C is wrong because `bytes(data)` creates a copy of the bytes object, not a string, so it does not perform any conversion. Option D is wrong because `str(data)` returns a string representation like `b'...'` (including the `b` prefix and escapes), not the actual decoded text.