Exercises
Text and Unicode
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Print how many characters the word has, then how many bytes it takes in UTF-8.
Python
word = "Müller"
# print the character count, then the byte count
len() on the str, then len() on the encoded bytes.
word = "Müller"
print(len(word))
print(len(word.encode("utf-8")))Exercise 2Passed
Decode the bytes back to text, and print the result.
Python
data = "café".encode("utf-8")
# print the text again
bytes have a decode method that takes the same encoding.
data = "café".encode("utf-8")
print(data.decode("utf-8"))Exercise 3Passed
These bytes are not valid UTF-8. Decode them without crashing, keeping a marker for what was lost.
Python
data = b"caf\xff"
# print a decoded version that does not raise
decode takes an errors argument.
data = b"caf\xff"
print(data.decode("utf-8", errors="replace"))