Repository navigation
Expand file tree
/
Copy pathunicode_and_bytes.py
More file actions
137 lines (107 loc) · 5.01 KB
/
Copy pathunicode_and_bytes.py
File metadata and controls
137 lines (107 loc) · 5.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
"""Unicode text and raw bytes: two different types, and how to cross between them.
A `str` is a sequence of *code points*: numbers that Unicode assigns to every
character, from "A" (65) to "€" (8364) to emoji. A `bytes` object is a
sequence of small integers 0-255, which is what files, sockets and disks
actually store.
To go from text to bytes you *encode*, choosing an encoding; to go back you
*decode* with the same encoding. UTF-8 is the usual choice: ASCII characters
take one byte each, and other characters take two, three or four.
Python never mixes the two silently. Adding a str to a bytes is a TypeError,
which forces you to decide the encoding once, at the edge of your program:
decode as data comes in, work with str inside, encode as it goes out.
"""
import unicodedata
def code_points_demo() -> None:
# ord() gives a character's code point; chr() goes the other way.
for ch in ["A", "a", "é", "€", "π"]:
print(f"{ch!r}: ord = {ord(ch):>5} hex = U+{ord(ch):04X}")
print(f"chr(9731) = {chr(9731)}")
# \u escapes write a code point by number inside a normal string.
print(f"'\\u00e9' == 'é' -> {'\u00e9' == 'é'}")
# Letters are numbers, so you can do arithmetic on them.
shifted = "".join(chr(ord(c) + 1) for c in "HAL")
print(f"HAL shifted by one: {shifted}")
def str_vs_bytes_demo() -> None:
text = "café"
data = text.encode("utf-8")
print(f"str {text!r}: type {type(text).__name__}, len {len(text)}")
print(f"bytes {data!r}: type {type(data).__name__}, len {len(data)}")
# Indexing bytes gives an int, not a one-character string.
print(f"text[0] = {text[0]!r}, data[0] = {data[0]!r}")
print(f"list(data) = {list(data)}")
# A b"..." literal may only contain ASCII; anything else needs escapes.
print(f"b'hi' == 'hi'.encode() -> {b'hi' == 'hi'.encode()}")
# Decoding with the same encoding round-trips exactly.
print(f"decoded back: {data.decode('utf-8')!r}")
# The two types never mix by accident.
try:
"price: " + b"10" # type: ignore[operator]
except TypeError as exc:
print(f"TypeError: {exc}")
def utf8_lengths_demo() -> None:
# UTF-8 is variable width: the higher the code point, the more bytes.
print(f"{'code point':<11} {'bytes':<6} {'encoded':<12} char")
for ch in ["A", "é", "€", "\U0001D11E"]:
encoded = ch.encode("utf-8")
point = f"U+{ord(ch):04X}"
print(f"{point:<11} {len(encoded):<6} {encoded.hex(' '):<12} {ch}")
# So len() of a string and len() of its bytes can differ a lot.
word = "naïve café"
print(f"{word!r}: {len(word)} characters, "
f"{len(word.encode('utf-8'))} UTF-8 bytes, "
f"{len(word.encode('utf-16-le'))} UTF-16 bytes")
# Cutting bytes in the middle of a character makes them undecodable.
cut = "€".encode("utf-8")[:2]
try:
cut.decode("utf-8")
except UnicodeDecodeError as exc:
print(f"UnicodeDecodeError: {exc}")
def error_handlers_demo() -> None:
# ASCII only covers code points 0-127, so "é" cannot be encoded in it.
text = "café"
try:
text.encode("ascii")
except UnicodeEncodeError as exc:
print(f"UnicodeEncodeError: {exc}")
# errors= says what to do instead of raising.
for handler in ["ignore", "replace", "xmlcharrefreplace", "backslashreplace"]:
print(f"encode errors={handler!r:<20} -> {text.encode('ascii', handler)!r}")
# Decoding has the same choices. Latin-1 bytes are not valid UTF-8.
latin1 = text.encode("latin-1")
print(f"latin-1 bytes: {latin1!r}")
for handler in ["replace", "backslashreplace"]:
print(f"decode errors={handler!r:<18} -> {latin1.decode('utf-8', handler)!r}")
# "replace" inserts U+FFFD, the official "something was lost here" mark.
# Prefer fixing the encoding to hiding the problem.
def normalize_demo() -> None:
# "é" can be one code point, or "e" followed by a combining accent.
composed = "caf\u00e9"
decomposed = "cafe\u0301"
print(f"{composed} vs {decomposed}: look the same, equal? "
f"{composed == decomposed}")
print(f"lengths: {len(composed)} and {len(decomposed)}")
for ch in decomposed[-2:]:
print(f" U+{ord(ch):04X} {unicodedata.name(ch)}")
# Normalising both to the same form makes the comparison honest.
# NFC composes into single code points; NFD splits them apart.
nfc_a = unicodedata.normalize("NFC", composed)
nfc_b = unicodedata.normalize("NFC", decomposed)
print(f"after NFC: equal? {nfc_a == nfc_b}, lengths {len(nfc_a)}, {len(nfc_b)}")
# A common trick: NFD, then drop the combining marks, to strip accents.
plain = "".join(
ch for ch in unicodedata.normalize("NFD", "Ångström café")
if not unicodedata.combining(ch)
)
print(f"accents stripped: {plain}")
def main() -> None:
code_points_demo()
print()
str_vs_bytes_demo()
print()
utf8_lengths_demo()
print()
error_handlers_demo()
print()
normalize_demo()
if __name__ == "__main__":
main()