Encode Text and Decode Bytes
Core idea
Encoding converts str to bytes according to a named encoding; decoding reverses that conversion when the bytes are valid. Use UTF-8 explicitly at system boundaries. Bytes are integer sequences with values from 0 to 255.
s = "سلام"raw = s.encode("utf-8")print(len(s), len(raw))print(raw.decode("utf-8") == s)Four Persian letters occupy eight UTF-8 bytes here.
Inspect an encoded value
raw = "é".encode("utf-8")print(raw.hex())print(list(raw))hex and list expose the actual bytes rather than their text rendering.
Common mistake
Do not use str(raw) to decode a byte sequence; it gives a representation with a bytes prefix. Choose the encoding agreed with the producer.
Practice
Return the UTF-8 byte count of a text field; compare empty, ASCII, Persian and emoji inputs.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Text and byte boundaries
Check your understanding of encoding and decoding.
What is printed?
print(len("é".encode("utf-8")))What is printed?
print(b"\xc3\xa9".decode("utf-8") == "é")Which method converts str into bytes?
What must a receiver know to decode bytes correctly?