Sub topic 16
Unicode Text Versus Bytes
This chapter assumes you can run Python code, use print(), and index and slice strings. It covers the difference between str and bytes, and how to convert between them explicitly.
Two different types
A str is a sequence of Unicode characters. A bytes object is a sequence of integers from 0 to 255. Text becomes bytes only when you choose an encoding, which is a rule that maps characters to byte values. UTF-8 is the most common encoding and the default for Python source files.
Files, network sockets, and many APIs deal in bytes. Your program's logic usually works better with str. The usual practice is to decode bytes to text when data comes in, work with text, and encode back to bytes when data goes out.
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"))This prints:
4
b'caf\xc3\xa9'
5
caféThe string has 4 characters. In UTF-8, the letter é takes two bytes (\xc3\xa9), so the encoded form is 5 bytes long. The b prefix in the output marks a bytes object. Plain ASCII characters such as c, a, and f take one byte each and are displayed as themselves.
So len() means different things for the two types. For a str it counts characters (strictly, Unicode code points). For bytes it counts bytes.
Choosing the encoding
Decoding needs the same encoding that was used to encode. If you pick the wrong one, you get either an error or garbled text.
data = "café".encode("utf-8")
print(data.decode("latin-1"))
try:
"café".encode("ascii")
except UnicodeEncodeError as e:
print("UnicodeEncodeError:", e.reason)Decoding UTF-8 bytes as Latin-1 does not fail, because Latin-1 maps every byte to some character. It prints café instead. This silent corruption is called mojibake. Encoding é as ASCII fails, because ASCII only covers code points 0 to 127.
Handling bad data
When bytes are not valid in the chosen encoding, decode() raises UnicodeDecodeError. The errors argument controls what happens instead.
bad = b"caf\xe9"
try:
bad.decode("utf-8")
except UnicodeDecodeError as e:
print("UnicodeDecodeError:", e.reason)
print(bad.decode("utf-8", errors="replace"))
print(bad.decode("latin-1"))With errors="replace", each bad byte becomes the replacement character �. This keeps the program running but loses information. The better fix is to find out which encoding the data actually uses. Here the byte \xe9 is é in Latin-1.
Differences between str and bytes
| Feature | `str` | `bytes` |
|---|---|---|
| Holds | Unicode characters | Integers 0 to 255 |
| Literal | `"abc"` | `b"abc"` |
| Indexing `x[0]` | A one-character `str` | An `int` |
| Immutable | Yes | Yes |
| Convert with | `.encode()` | `.decode()` |
Mixing the two is an error. "a" + b"b" raises TypeError, and "a" == b"a" is False without any warning. Convert one side first.
Common mistakes
- Calling
len()on encoded data and expecting a character count. - Opening a file in binary mode (
"rb") and then treating the result as text. - Using
errors="ignore"orerrors="replace"to silence an error without finding the real encoding. - Comparing
strandbytesvalues and expecting a match.
Exercise
The string s = "naïve" has 5 characters. What does len(s.encode("utf-8")) return, and why? What does s.encode("utf-8").decode("ascii") do?
Show answer
It returns 6, because ï takes two bytes in UTF-8 and the other four characters take one byte each. Decoding with "ascii" raises UnicodeDecodeError, because the two bytes for ï are above 127 and are not valid ASCII.
Exercise
You read the bytes b"price: \xe2\x82\xac5" from a network connection. Write the line of Python that turns them into text, and say which encoding you assumed.
Show answer
b"price: \xe2\x82\xac5".decode("utf-8") gives 'price: €5'. The assumed encoding is UTF-8, where the euro sign is the three bytes \xe2\x82\xac.