Python 3D Academyবাংলা

Text and encodings: Unicode, UTF-8 and bytes

🌍 In real life. In the days of the telegraph, a message was sent as dots and dashes, and the clerk at the other end had to use the same code book to turn them back into letters. With the wrong code book, "চা পাঠাও" arrived as nonsense.

A computer has the same problem. A file or a network message holds only numbers, and an encoding is the code book that turns letters into numbers and back. When a Bangla name shows up as রহিম, someone read it with the wrong code book. This lesson shows how to always use the right one.

The idea in one sentence: a str is a row of Unicode characters; to save or send it, Python encodes it into bytes with an encoding, and decodes bytes back with the same one, and the one to use is UTF-8, so always write encoding="utf-8" when you open a text file.

Its words:

  • Unicode: one big numbered list of every character in every script: ord("আ") is 2438, and chr(2438) is "আ"
  • bytes: raw numbers from 0 to 255, written like b'\xe0\xa6\x9a'
  • encoding: the rule for turning characters into bytes; UTF-8 uses 1 byte for an English letter and 3 for a Bangla one
  • text.encode("utf-8") gives bytes; data.decode("utf-8") gives the text back

Step by step, for the name রহিম:

  1. As a str it has 4 characters: র, হ, the vowel sign ি, and ম. A vowel sign is a character of its own.
  2. encode("utf-8") turns each one into 3 bytes: 12 bytes in all.
  3. Those 12 bytes are what a file or a network really stores.
  4. decode("utf-8") turns the same 12 bytes back into the same 4 characters.
word = "চা"
print([ord(ch) for ch in word])
data = word.encode("utf-8")
print(data, len(data))
print(data.decode("utf-8"))
print("tea".encode("utf-8"))
Each character has one Unicode number. In UTF-8, চ and া take 3 bytes each; t, e and a take 1 each, so English text looks the same as bytes.

Files: say the encoding every time. open() turns your text into bytes using an encoding. If you don't name one, Python uses the computer's default. That is UTF-8 on macOS, Linux and in this app, but on Windows, Python 3.14 and earlier often use an old code page such as cp1252, which has no Bangla letters at all. The same program that works on a friend's Mac then stops on a Windows PC with UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-3: character maps to <undefined>. Naming the encoding makes the program behave the same everywhere:

  • open("names.txt", "w", encoding="utf-8") and open("names.txt", encoding="utf-8")
  • Path("names.txt").read_text(encoding="utf-8") and write_text(text, encoding="utf-8")
  • CSV files: open("marks.csv", newline="", encoding="utf-8")
with open("names.txt", "w", encoding="utf-8") as f:
    f.write("রহিম\nকরিম\n")

with open("names.txt", encoding="utf-8") as f:
    for line in f:
        name = line.strip()
        print(name, len(name))

JSON keeps Bangla readable only if you ask. json.dumps writes every non-English character as a \u code by default. Python reads that back correctly, but a person opening the file sees \u09b0\u09b9\u09bf\u09ae instead of রহিম. Pass ensure_ascii=False to keep the letters, and write the file with encoding="utf-8".

import json

contact = {"name": "রহিম", "city": "ঢাকা"}
print(json.dumps(contact))
print(json.dumps(contact, ensure_ascii=False))

with open("contact.json", "w", encoding="utf-8") as f:
    json.dump(contact, f, ensure_ascii=False)
with open("contact.json", encoding="utf-8") as f:
    print(json.load(f)["city"])

What it costs. UTF-8 makes English text no bigger than before and Bangla text 3 bytes a character; encode and decode are one pass over the text, O(n). Getting it wrong costs far more: names your users can't read.

Mistakes and edge cases.

  • Reading with the wrong code book. UTF-8 bytes read as ASCII give UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 0: ordinal not in range(128). Read as latin-1 they don't fail at all: they quietly turn into রহিম, which is worse.
  • Writing Bangla with an old code page. encoding="cp1252" (or a Windows default) gives the UnicodeEncodeError above.
  • Mixing str and bytes. "a" + b"b" gives TypeError: can only concatenate str (not "bytes") to str. Decode the bytes first.
  • Cutting bytes in the middle of a character. data[:2].decode("utf-8") on Bangla gives UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 0-1: unexpected end of data. Slice the str, not the bytes.
  • Expecting len to count what you see. len("রহিম") is 4, not 3: vowel signs are characters of their own.

Quiz

  1. What does this print?

    word = "চা"
    print(len(word), len(word.encode("utf-8")))
  2. Why write encoding="utf-8" when you open a text file?

    • Without it Python uses the computer's default, which on many Windows PCs can't store Bangla
    • It makes the file smaller
    • open() fails without an encoding
  3. What does this print?

    import json
    
    print(json.dumps(["চা"], ensure_ascii=False))
  4. This should print চা 15, but it prints strange letters. Which line is wrong?

    with open("menu.txt", "w", encoding="utf-8") as f:
        f.write("চা 15\n")
    
    with open("menu.txt", encoding="latin-1") as f:
        print(f.read())
  5. What is b'\xe0\xa6\x9a'?

    • bytes: three numbers from 0 to 255, here the UTF-8 code for চ
    • A str with three characters
    • A broken string that Python can't use

Coding tasks

  1. Write utf8_size(text): how many bytes the text takes in UTF-8.

  2. Write save_contact(contact, path): save the dict to the file as JSON, keeping Bangla letters readable (no \u codes), in UTF-8.