Skip to the solution
MediumDSA12 min read

What is the difference between bytes and str?

1.1k views

The problem

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:

  • str is an immutable sequence of Unicode code points (text); bytes is an immutable sequence of integers 0 to 255 (binary data)
  • str.encode(encoding) gives bytes; bytes.decode(encoding) gives str; 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 a TypeError and b"abc" == "abc" is False; indexing bytes returns an int
  • Errors: UnicodeEncodeError, UnicodeDecodeError, and the errors= 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 str inside, encode at the output boundary
  • Related: bytearray (mutable), memoryview (zero-copy slices), and CPython storing str at 1, 2 or 4 bytes per character (PEP 393)

Code / implementation expected: Optional — an encode/decode round trip and one error case.

  • bytes
  • str
  • encoding

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read · 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythonencode and decode, indexing, codecs, errors and why Python 3 refuses to mix the types
PythonUnder the hood: PEP 393 storage widths, code points vs visible characters, normalisation, memoryview

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 44 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What is the Global Interpreter Lock (GIL)?

Continue