Sub topic 16
Unicode Text versus Bytes
This chapter assumes you can index, slice, and call methods on strings, use f-strings, and handle exceptions with try/except. It adds one distinction. A str is text, and bytes is raw data. Python converts between them only when you ask it to.
Two types, two jobs
A str is a sequence of Unicode code points. A code point is a number that Unicode assigns to a character, such as é, €, or 😀. A bytes object is a sequence of integers from 0 to 255. Files, sockets, and network messages store and carry bytes, not text.
An encoding is a rule that maps text to bytes. Encoding turns str into bytes. Decoding turns bytes back into str. Python 3 never converts between them silently.
| Property | `str` | `bytes` |
|---|---|---|
| Holds | Unicode code points | Integers 0 to 255 |
| Literal | `"café"` | `b"abc"` (ASCII characters only) |
| `len()` counts | Characters (code points) | Bytes |
| Indexing returns | A one-character `str` | An `int` |
| Mutable? | No | No (`bytearray` is the mutable form) |
Encoding and decoding
The .encode() method on a str returns bytes. The .decode() method on bytes returns a str.
text = "café"
print(len(text))
data = text.encode("utf-8")
print(data)
print(len(data))
print(data.decode("utf-8"))The text has 4 characters but the encoded form has 5 bytes. The output is 4, then b'caf\xc3\xa9', then 5, then café. The character é takes two bytes, \xc3\xa9. len() on a str counts characters, and on bytes it counts bytes. These can differ.
Code points and UTF-8 sizes
ord() gives the code point of a character. UTF-8 is a variable-width encoding, so it uses 1 to 4 bytes per code point. ASCII characters take one byte, and rarer characters take more.
for ch in "aé€😀":
print(ch, hex(ord(ch)), len(ch.encode("utf-8")))This prints a 0x61 1, é 0xe9 2, € 0x20ac 3, and 😀 0x1f600 4. UTF-8 is the right default for new data. It is compact for English text, it can represent every code point, and the web and most modern tools use it.
You can also write characters by escape inside a normal string. "\u00e9" is é, and "\N{EURO SIGN}" is €.
The same text in different encodings
Different encodings produce different bytes for the same text. Decoding with the wrong one gives garbled text (called mojibake) or an error.
s = "café"
print(s.encode("latin-1"))
print(s.encode("utf-16-le"))
print(s.encode("utf-8").decode("latin-1"))The output is b'caf\xe9', then b'c\x00a\x00f\xe9\x00', then café. Latin-1 uses one byte per character here. UTF-16 uses two. The last line shows the classic mojibake: UTF-8 bytes read as Latin-1. Nothing raised an error, because every byte value is valid in Latin-1. The decode succeeded and the text is wrong.
Bytes do not record which encoding produced them. You must know it from a file format, a protocol header, or an agreement with the other side.
When conversion fails
Encoding fails when the target encoding cannot represent a character. Decoding fails when the bytes are not valid in the encoding.
try:
"café".encode("ascii")
except UnicodeEncodeError as e:
print("encode failed:", e.reason)
try:
b"\xffabc".decode("utf-8")
except UnicodeDecodeError as e:
print("decode failed:", e.reason)This prints encode failed: ordinal not in range(128) and decode failed: invalid start byte. Both exceptions are subclasses of ValueError.
Both methods accept an errors argument that chooses a fallback instead of raising.
print("café".encode("ascii", errors="replace"))
print("café".encode("ascii", errors="ignore"))
print("café".encode("ascii", errors="xmlcharrefreplace"))
print(b"caf\xe9".decode("utf-8", errors="replace"))The output is b'caf?', b'caf', b'café', and caf�. The last line uses the replacement character U+FFFD for the byte that is not valid UTF-8.
Working with bytes directly
Indexing bytes returns an integer, not a one-byte object. Slicing returns bytes.
data = b"abc"
print(data[0])
print(data[0:2])
print(list(data))
print(b"abc" == "abc")
try:
data + "d"
except TypeError:
print("cannot mix bytes and str")The output is 97, b'ab', [97, 98, 99], False, and the message. A bytes literal can contain only ASCII characters, so b"café" is a SyntaxError. Write "café".encode() instead, which uses UTF-8 by default. Comparing bytes with str is always False, and it does not raise. This is a quiet source of bugs when a value you expected to be text is actually bytes.
bytes has many methods in common with str, such as .split(), .replace(), and .startswith(), but they take bytes arguments. There are no f-strings for bytes. To change bytes in place, use bytearray.
Files and the boundary rule
Text mode in open() decodes on read and encodes on write. Binary mode ("rb", "wb") gives you raw bytes.
with open("note.txt", "w", encoding="utf-8") as f:
f.write("café\n")
with open("note.txt", "rb") as f:
print(f.read())
with open("note.txt", encoding="utf-8") as f:
print(f.read(), end="")The output is b'caf\xc3\xa9\n' and then café. If you omit encoding, the default comes from the platform. On Windows it is often a legacy code page such as cp1252. Newer Python releases move toward UTF-8 as the default, but passing encoding="utf-8" works the same everywhere. Always pass it.
A reliable design is to decode bytes to str as soon as data enters your program. Work with str everywhere inside. Encode back to bytes only when data leaves. Programmers sometimes call this the Unicode sandwich.
Normalization: one character, two spellings
Unicode can represent some characters in more than one way. The letter é can be one code point, or an e followed by a combining accent. They look identical but are different strings.
import unicodedata
a = "\u00e9"
b = "e\u0301"
print(a, b)
print(a == b)
print(len(a), len(b))
print(unicodedata.normalize("NFC", b) == a)The output is é é, False, 1 2, and True. The NFC form composes characters into single code points where possible. Normalize text with unicodedata.normalize before comparing or using it as a dictionary key when it comes from users, files, or different operating systems. Even then, len() counts code points, not what a reader sees as a character. Some emoji and accented letters are several code points.
Common mistakes
- Treating
len()of bytes as a character count. Decode first. - Calling
.encode()onbytes, or.decode()onstr. Each method exists only on one type, so you get anAttributeError. - Decoding with a guessed encoding. A wrong guess may succeed and produce mojibake.
- Opening a text file without
encoding, which makes the program behave differently on different machines. - Comparing
bytestostrand expecting a match.
Exercise
The string "naïve" has 5 characters. How many bytes is it in UTF-8, and what does "naïve".encode("ascii", errors="ignore") return?
Show answer
It is 6 bytes, because ï (U+00EF) takes two bytes in UTF-8 and the other four characters take one each. The ASCII call drops the character that ASCII cannot represent and returns b'nave'.
Exercise
A program reads a file in binary mode and gets b"caf\xc3\xa9". A colleague decodes it with .decode("latin-1") and gets café with no error. Why did no error occur, and what is the fix?
Show answer
Every byte value from 0 to 255 is valid in Latin-1, so decoding cannot fail, but it maps the two UTF-8 bytes to two separate characters. The file was written as UTF-8, so the fix is .decode("utf-8"), which returns café.