Why can one character take several bytes in UTF-8?
Quick answer
UTF-8 encodes Unicode code points using a variable number of bytes: code points below 128 use one byte, while other code points use two, three, or four. That means a string’s byte size depends on the code points it contains, not just their number. To work it out, add the UTF-8 byte counts for each code point in the text. [S1]
The question, the details, the next step.
A practical checklist
Use the exact text you need to measure.
Confirm that UTF-8 is the required encoding.
Count bytes in the encoded text, rather than assuming one byte per code point.
Add the byte lengths for the text’s code points.
Check whether a stated limit is measured in bytes or another unit.
A few more useful answers
How many bytes can a UTF-8 code point use?
One, two, three, or four bytes. Code points below 128 use one byte; other code points use sequences of two, three, or four bytes. [S1]
Will two strings with the same number of code points always use the same number of UTF-8 bytes?
No. Their code points may have different UTF-8 byte lengths, so the totals can differ even when the code-point counts are the same. [S1]
What is the quickest way to estimate a string’s UTF-8 size?
Identify the UTF-8 byte length of each code point in the exact text and add the lengths. The result depends on the text, not only its code-point count. [S1]
Sources
References used for this guide.
- [S1] Unicode HOWTO — Python documentation docs.python.org · Checked
