Question presented to candidate:
"In Python 3, what is the difference between bytes and str? When do you get each one, how do you convert between them, and what goes wrong when people mix them up?"
What a strong answer should cover:
stris an immutable sequence of Unicode code points (text);bytesis an immutable sequence of integers 0 to 255 (binary data)str.encode(encoding)givesbytes;bytes.decode(encoding)givesstr; UTF-8 is the usual encoding, and the same text has different byte lengths in different encodings- Python 3 never converts implicitly:
"a" + b"a"is aTypeErrorandb"abc" == "abc"isFalse; indexingbytesreturns anint - Errors:
UnicodeEncodeError,UnicodeDecodeError, and theerrors=argument (strict,replace,ignore); decoding with the wrong codec can silently produce mojibake - The "Unicode sandwich": decode at the input boundary (files, sockets, HTTP), work with
strinside, encode at the output boundary - Related:
bytearray(mutable),memoryview(zero-copy slices), and CPython storingstrat 1, 2 or 4 bytes per character (PEP 393)
Code / implementation expected: Optional — an encode/decode round trip and one error case.