Python Unicode, Encodings and Bytes
What you will learn
- What Unicode and code points are, with
ord()andchr() - Why
len()counts code points, and why that can surprise you - What normalisation does for accents
- The difference between
str(text) andbytes(raw data) - How to encode and decode, and what UTF-8 is
- The common errors, and mojibake
- The rules that keep text safe
1. Characters and code points
A computer stores only numbers. Unicode is the worldwide table that gives every character a number, called its code point. It covers letters of almost every language, digits, symbols and emoji. A Python str is a sequence of Unicode characters.
ord() gives the code point of a character, and chr() goes back:
print(ord("A"), ord("é"), ord("€"), ord("😀"))
print(chr(65), chr(233), chr(0x1F600))
print(hex(ord("€")))
65 233 8364 128512
A é 😀
0x20ac
You can write any character by its code point inside a string with an escape:
| Escape | Meaning | Example |
|---|---|---|
\xhh |
2 hex digits | "\xe9" is é |
\uhhhh |
4 hex digits | "\u20ac" is € |
\Uhhhhhhhh |
8 hex digits | "\U0001F600" is 😀 |
\N{name} |
the official name | "\N{SNOWMAN}" is ☃ |
print("\u20ac" == "€", "\U0001F600" == "😀")
True True
Quick check: what is `chr(ord("a") - 32)`?
"A". In the code table, lower-case letters are 32 above their capitals.
2. What len() really counts
len() counts code points, not what you see on the screen:
print(len("héllo"), len("😀"))
print(len("é"), len("é"))
print("é" == "é")
5 1
2 1
False
The text "é" shows as é, but it is two code points: the letter e followed by a combining accent. The single character "é" looks the same but is one code point, so the two strings are not equal. Emoji can be longer still: len("🇧🇩") (a flag) is 2, and a family emoji joined with invisible joiners can be 5.
3. Normalisation
Because the same text can be written in more than one way, unicodedata.normalize converts it to a standard form:
| Form | Meaning |
|---|---|
"NFC" |
combine into single characters where possible (é as one code point) |
"NFD" |
split into base letter plus combining marks |
import unicodedata
a = "é"
b = "é"
print(a == b)
print(unicodedata.normalize("NFC", b) == a)
print(len(unicodedata.normalize("NFC", b)), len(unicodedata.normalize("NFD", a)))
False
True
1 2
Normalise text before comparing it, especially text typed by users or read from files. The same module can name any character, and a clever use of NFD is to strip accents: split into letters and marks, then drop the marks (category Mn):
import unicodedata
print(unicodedata.name("é"), "|", unicodedata.name("€"))
text = unicodedata.normalize("NFD", "café")
print("".join(c for c in text if unicodedata.category(c) != "Mn"))
LATIN SMALL LETTER E WITH ACUTE | EURO SIGN
cafe
4. str and bytes
A str is text. A bytes object is raw data: a sequence of numbers from 0 to 255. Files, networks and databases hold bytes. Turning text into bytes is encoding; turning bytes into text is decoding:
text (str) ── encode ──▶ bytes
text (str) ◀── decode ── bytes
b = "héllo".encode("utf-8")
print(b, type(b), len(b))
print(b[0], list(b[:3]))
print(b.decode("utf-8"))
b'h\xc3\xa9llo' <class 'bytes'> 6
104 [104, 195, 169]
héllo
- The
bin front of the quotes means bytes. Characters outside the plain range are shown as\x..escapes. "héllo"is 5 characters but 6 bytes: theétakes two bytes.- Indexing a
bytesobject gives a number, not a character.
str and bytes do not mix:
"a" + b"b"
TypeError: can only concatenate str (not "bytes") to str
And b"a" == "a" is False. Always decode or encode explicitly.
5. Encodings and UTF-8
An encoding is a rule for turning characters into bytes. The one to use is UTF-8: it can write every Unicode character, and it is the standard of the web. It uses 1 to 4 bytes per character:
for ch in ["A", "é", "€", "😀"]:
data = ch.encode("utf-8")
print(ch, len(data), data.hex(" "))
A 1 41
é 2 c3 a9
€ 3 e2 82 ac
😀 4 f0 9f 98 80
| Character | UTF-8 bytes |
|---|---|
| plain English letters and digits | 1 (same as old ASCII) |
accented letters such as é |
2 |
many symbols such as € and most Asian letters |
3 |
| emoji and rare characters | 4 |
Older encodings cover only some characters. "ascii" knows only 128, and "latin-1" (one byte per character) only 256. utf-16 and utf-32 use more bytes per character. Python's default is UTF-8: sys.getdefaultencoding() gives 'utf-8', and .encode() with no argument uses it.
6. Errors, and the error handlers
Encoding with an encoding that cannot write a character fails. So does decoding bytes that are not valid in that encoding:
"€".encode("ascii")
UnicodeEncodeError: 'ascii' codec can't encode character '\u20ac' in position 0: ordinal not in range(128)
b"\xff".decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
The errors option chooses what to do instead of stopping. Use it with care, because it loses or changes data:
print("€".encode("ascii", errors="replace"))
print("€".encode("ascii", errors="ignore"))
print("€".encode("ascii", errors="backslashreplace"))
print("café".encode("ascii", errors="xmlcharrefreplace"))
print(b"ab\xffcd".decode("utf-8", errors="ignore"))
b'?'
b''
b'\\u20ac'
b'café'
abcd
| Handler | Effect |
|---|---|
"strict" (default) |
raise an error |
"replace" |
put ? (or the official replacement character when decoding) |
"ignore" |
drop the character |
"backslashreplace" |
write the escape, such as \u20ac |
"xmlcharrefreplace" |
write an HTML code such as é |
7. Mojibake: the wrong decoder
If you decode bytes with the wrong encoding, you get nonsense characters called mojibake:
data = "é".encode("utf-8")
print(data.decode("latin-1"))
é
The two UTF-8 bytes of é were read as two separate old-style characters. If you ever see é where é should be, someone decoded UTF-8 text with the wrong encoding.
8. bytearray
bytes is immutable, like str. bytearray is its mutable version, which you can change in place:
ba = bytearray(b"abc")
ba[0] = 65
print(ba, bytes(ba))
bytearray(b'Abc') b'Abc'
bytes can also be made from numbers, bytes([72, 105]) is b'Hi', or from hex text, bytes.fromhex("c3a9").
9. Rules for keeping text safe
- Decode as early as possible (when you read data in), work with
strinside your program, and encode as late as possible (when you write data out). - Always say the encoding when you open a text file,
open(name, encoding="utf-8")(chapter 15), because the default can depend on the computer. - Normalise before comparing text from different sources.
- Never guess: if you do not know the encoding of some bytes, find out from the source.
- Sort carefully. Python sorts by code point, so
"é" > "z"isTrue, and capitals come first. For language-aware sorting, comparecasefold()text or use a locale-aware tool.
A note for Windows users: in the tests for this lesson, printing a character such as π with the output sent into a pipe failed with UnicodeEncodeError: 'charmap' codec can't encode..., because the output used an old code page. Setting the environment variable PYTHONIOENCODING=utf-8 fixed it. Typing into a normal terminal window is usually fine.
Worked example: characters versus bytes
How long is the text "naïve café €5" as characters, and how big is it when sent as UTF-8?
text = "naïve café €5"
data = text.encode("utf-8")
print(len(text), len(data))
print(data.decode("utf-8") == text)
13 17
True
| Character | Bytes |
|---|---|
10 plain characters (letters, spaces, 5) |
1 each = 10 |
ï and é |
2 each = 4 |
€ |
3 |
| total | 17 |
There are 13 characters but 17 bytes. Decoding gives back exactly the same text. When a form or database says "limit of 20 characters", check whether it counts characters or bytes.
Common mistakes
- Treating
len(bytes)as the number of characters. - Mixing
strandbyteswith+or==. - Forgetting
encoding="utf-8"when opening files. - Using
errors="ignore"and silently losing data. - Comparing text without normalising, so
"é"and"é"seem different. - Decoding with a guessed encoding, which produces mojibake.
Key takeaways
- Unicode gives every character a code point;
ordandchrconvert, and\u,\Uand\N{}write them. len()counts code points; combining marks and emoji make it differ from what you see; normalise withunicodedata.normalize.stris text andbytesis raw data;encodeturns text into bytes anddecodeturns bytes into text.- UTF-8 uses 1 to 4 bytes per character and can write all of Unicode; use it by default.
- Decode early, work in
str, encode late; always name the encoding when opening files.
Practice
1. What are ord("a") and chr(100)?
Show answer
97 and "d".
2. How many bytes does "€" take in UTF-8, and how many characters is it?
Show answer
3 bytes, 1 character.
3. Why is "é" == "é" false, and how do you make the comparison fair?
Show answer
They are different code points: one character versus a letter plus a combining accent. Normalise both with unicodedata.normalize("NFC", ...) before comparing.
4. What does b"hi".decode() give, and what does "hi".encode() give?
Show answer
"hi" (text) and b"hi" (bytes).
5. The text "é" appears where you expected "é". What probably went wrong?
Show answer
UTF-8 bytes were decoded with the wrong encoding (such as Latin-1). Decode them as UTF-8.
6. Write the line that opens notes.txt for reading with the right encoding.
Show answer
open("notes.txt", encoding="utf-8").