Does len() count characters or bytes?
Neither, strictly. len(s) counts code points. For ASCII that happens to equal both the byte count and what a reader would call characters, which is why the distinction stays hidden until an accent or an emoji arrives.
Overview
Three different counts
There are three things you could mean by "length", and they coincide only for ASCII:
Code points — what len(s) returns. A Python 3 str is a sequence of code points, and indexing gives you one.
Bytes — len(s.encode('utf-8')). Depends entirely on the encoding, which is why the encoding has to be named. This is the number that matters for a database column or a network frame.
Grapheme clusters — what a human counts. Python has no built-in for this; it needs a library.
Step through it
What to watch
- The second and third rows look the same and are not equal.
- One is
éas a single code point, the other iseplus a combining mark. - Normalising is what makes the comparison behave.
Say this out loud
"len counts code points. Bytes is len(s.encode('utf-8')), and neither is what a user calls a character once you have combining accents or emoji."