str vs bytes¶
Level: 101 · for Python programmers
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The bullets below are the questions the finished page has to answer.
One line: str is a sequence of code points and bytes is a sequence of numbers 0..255; they never mix, and TypeError: can't concat str to bytes is the boundary refusing to be crossed silently.
What the finished page has to answer¶
- Indexing each:
'café'[3]is'é',b'caf\xc3\xa9'[3]is195— a character versus a number lenon each, and why they differ by exactly the number of non-ASCII characters' extra bytes- Literals:
'…',b'…', and whyb'é'is a syntax error reprof each: what Python shows you, and whyb'A'is a display choice, not a fact about the bytebytearrayandmemoryview: the mutable and the zero-copy views of the same numbers — now written next door asbytearrayis the mutable one ↗, so this page should point at it rather than repeat it- One line of history: Python 2's
strwas bytes, and everyu''prefix in old code is that scar
The example it will run¶
Python: the same four strings as str and as bytes, indexed, sliced, measured, and concatenated with each other until the TypeError.
See also¶
- Encode and decode are verbs
- Encode, decode and errors
bytearrayis the mutable one ↗ — the mutable half of the pair, and where mutability is recorded in six languages