Featurecore
Encoding and decoding
Also called str.encode, bytes.decode, character encoding, UTF-8, codecs, error handler, UnicodeDecodeError, UnicodeEncodeError, surrogateescape, UTF-8 Mode, mojibake.
str.encode() turns text into bytes, and bytes.decode() turns bytes into text. The encoding is UTF-8 by default. The errors argument decides what happens to data that does not fit.
- Language
- Python
Synopsis
text = "Gr\u00fc\u00dfe, \u4e16\u754c"
data = text.encode("utf-8")
print(data)
print(len(text), len(data))
print(data.decode("utf-8") == text)
b'Gr\xc3\xbc\xc3\x9fe, \xe4\xb8\x96\xe7\x95\x8c'
9 15
True
The text has 9 code points. UTF-8 uses 1 byte for each ASCII letter, 2 bytes for each of ü and ß, and 3 bytes for each of the two Chinese characters.
Semantics
r1. "The rules for translating a Unicode string into a sequence of bytes are called a character encoding, or just an encoding."1 "Encodings are specified as strings containing the encoding’s name."1
r2. str.encode() "returns a bytes representation of the Unicode string, encoded in the requested encoding."1 bytes.decode() goes the other way.1 For UTF-8: "If the code point is < 128, it’s represented by the corresponding byte value. If the code point is >= 128, it’s turned into a sequence of two, three, or four bytes".1
r3. The errors argument "specifies the response when the input string can’t be converted according to the encoding’s rules."1 The default is 'strict', which raises UnicodeError or a subclass.2 Examples: strict-decode, strict-encode.
r4. For decoding, 'replace' uses U+FFFD, 'ignore' leaves the data out, and 'backslashreplace' inserts a \xNN escape.1 For encoding, 'replace' inserts a question mark, and 'xmlcharrefreplace' and 'namereplace' are also available.1 Examples: decode-errors, encode-errors.
r5. 'surrogateescape' keeps bytes that do not decode. "On decoding, replace byte with individual surrogate code ranging from U+DC80 to U+DCFF. This code will then be turned back into the same byte when the 'surrogateescape' error handler is used when encoding the data."2 Example: round-trip.
r6. "The default encoding of TextIOWrapper and open() is UTF-8. If Python UTF-8 Mode is disabled, the default encoding is locale-specific (locale.getencoding())."3 PEP 540 added the mode: "When UTF-8 Mode is active, Python will: use the utf-8 encoding, regardless of the locale currently set by the current platform".5 PEP 686 made it the default.4
r7. "On decoding utf-8-sig will skip those three bytes if they appear as the first three bytes in the file. In UTF-8, the use of the BOM is discouraged and should generally be avoided."2 Example: bom.
Examples
data = b"\x80abc"
for handler in ["replace", "backslashreplace", "ignore"]:
print(handler, ascii(data.decode("utf-8", handler)))
replace '\ufffdabc'
backslashreplace '\\x80abc'
ignore 'abc'
The byte 0x80 cannot start a UTF-8 sequence. Each handler deals with it in its own way (rule r4).
u = chr(40960) + "abcd" + chr(1972)
for handler in ["ignore", "replace", "xmlcharrefreplace", "backslashreplace", "namereplace"]:
print(handler, u.encode("ascii", handler))
ignore b'abcd'
replace b'?abcd?'
xmlcharrefreplace b'ꀀabcd޴'
backslashreplace b'\\ua000abcd\\u07b4'
namereplace b'\\N{YI SYLLABLE IT}abcd\\u07b4'
raw = b"caf\xe9.txt"
name = raw.decode("utf-8", "surrogateescape")
print(ascii(name))
print(name.encode("utf-8", "surrogateescape") == raw)
'caf\udce9.txt'
True
The byte 0xe9 is not valid UTF-8 here. It becomes the code point U+DCE9 and comes back as the same byte (rule r5).
data = "hi".encode("utf-8-sig")
print(data)
print(ascii(data.decode("utf-8")), ascii(data.decode("utf-8-sig")))
b'\xef\xbb\xbfhi'
'\ufeffhi' 'hi'
The plain UTF-8 codec keeps the BOM as the code point U+FEFF. The utf-8-sig codec removes it (rule r7).
Pitfalls
Bytes that are not valid in the encoding raise an error:
This code raises UnicodeDecodeError, on purpose.
b"\x80abc".decode("utf-8")
Text that the encoding cannot hold raises an error:
This code raises UnicodeEncodeError, on purpose.
"caf\u00e9".encode("ascii")
The wrong encoding can decode without an error and give the wrong text:
This code runs but gives a wrong answer on purpose.
data = "caf\u00e9".encode("utf-8")
print(data.decode("latin-1"))
print(data.decode("utf-8"))
café
café
Latin-1 maps every byte to a code point, so it never fails. The two UTF-8 bytes of é become two Latin-1 characters. Decode with the encoding that wrote the data.
Code that reads files should name the encoding, as in open(path, encoding='utf-8'). PEP 686 gives the reason: "many Python developers using Unix forget that the default encoding is platform dependent."4 An older Python without UTF-8 Mode uses the locale encoding (rule r6).
Comparison
Go has no decode step for a string: "Go source code is always UTF-8. A string holds arbitrary bytes."6 A string can hold bytes that are not valid UTF-8, and only some operations decode them: "A for range loop, by contrast, decodes one UTF-8-encoded rune on each iteration."6 A Python str always holds code points, so bytes from a file or a socket must go through decode() first (rule r2).
References
- Unicode HOWTO, Python 3.15 documentation, Encodings; Converting to Bytes; The String Type
- codecs, Codec registry and base classes, Error Handlers; Encodings and Unicode
- io, Core tools for working with streams, Text encoding
- PEP 686: Make UTF-8 mode default, Abstract; Motivation
- PEP 540: Add a new UTF-8 Mode, Abstract
- Strings, bytes, runes and characters in Go, The Go Blog, Code points, characters, and runes; Range loops
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag T6N0E9 Edit this page History Report an error Markdown