Reading history

Python Bytes, Unicode and Encoding

7 min read 0 views

Understand str and bytes in Python, Unicode code points and UTF-8, encode and decode, Bangla text in files, and Unicode normalization.

Have you ever opened a file and seen strange symbols like ঢ where Bangla text should be? That happens when text is saved with one encoding and read with another. Python keeps text (str) and raw data (bytes) as two separate types, and moving between them is called encoding and decoding. Once you understand this, files, networks and Bangla text stop causing surprises.

In this lesson you will learn

  • The difference between str and bytes
  • Unicode code points and the UTF-8 encoding
  • encode(), decode() and handling bad bytes
  • Reading and writing text files with the right encoding
  • bytearray and Unicode normalization

You should know strings, file handling and binary and hexadecimal numbers.

Three Key Ideas

  • Unicode gives every character in every language a number, called a code point. “A” is U+0041 and the Bangla letter “ঢ” is U+09A2.
  • Computers store and send bytes, numbers from 0 to 255. An encoding is a rule for turning code points into bytes.
  • UTF-8 is the most common encoding on the web. It uses 1 byte for English letters, and 2 to 4 bytes for other characters. Bangla letters take 3 bytes each.
str (text you work with)DU+004444aU+006161ঢU+09A2E0A6A2কU+0995E0A695← Unicode code pointsbytes in UTF-8 (hex): 1 byte for English letters, 3 bytes for Bangla.encode(“utf-8”).decode(“utf-8”)

Encoding and Decoding

# str holds text (Unicode characters); bytes holds raw numbers 0-255
text = "Dhaka ঢাকা"
data = text.encode("utf-8")
print(type(text).__name__, len(text), "characters")
print(type(data).__name__, len(data), "bytes")
print(data)

# Each Bangla letter needs 3 bytes in UTF-8; English letters need 1
for ch in "Aঢ":
    b = ch.encode("utf-8")
    print(f"{ch!r}: code point U+{ord(ch):04X}, {len(b)} byte(s): {b.hex(' ')}")

# Decoding turns bytes back into text
print(data.decode("utf-8"))

# Decoding with the wrong encoding gives garbage or an error
print(data.decode("cp1252", errors="replace"))   # wrong code page: "mojibake"
try:
    data.decode("ascii")
except UnicodeDecodeError as e:
    print("UnicodeDecodeError:", e.reason)

# errors= decides what happens to bad bytes
broken = data[:-1]                         # cut the last byte off
print(broken.decode("utf-8", errors="replace"))
print(broken.decode("utf-8", errors="ignore"))

# ord and chr convert between characters and code points
print(ord("A"), chr(2453), chr(0x09E6 + 7))   # 0x09E6 is Bangla digit zero

Output

str 10 characters
bytes 18 bytes
b'Dhaka \xe0\xa6\xa2\xe0\xa6\xbe\xe0\xa6\x95\xe0\xa6\xbe'
'A': code point U+0041, 1 byte(s): 41
'ঢ': code point U+09A2, 3 byte(s): e0 a6 a2
Dhaka ঢাকা
Dhaka ঢাকা
UnicodeDecodeError: ordinal not in range(128)
Dhaka ঢাক�
Dhaka ঢাক
65 ক ৭
  • “Dhaka ঢাকা” is 10 characters but 18 bytes in UTF-8: 6 bytes for “Dhaka ” and 3 bytes for each of the 4 Bangla characters.
  • text.encode("utf-8") turns a str into bytes. A b'...' value shows readable bytes as letters and the rest as \x codes.
  • data.decode("utf-8") turns the bytes back into text.
  • Decoding with the wrong encoding gives either garbage, called mojibake, or a UnicodeDecodeError. ASCII only knows codes 0 to 127, so it fails at the first Bangla byte.
  • errors="replace" puts a � where bytes are broken. errors="ignore" drops them silently.
  • ord() gives a character’s code point, and chr() goes the other way.

Files, bytearray and Normalization

import tempfile, os, unicodedata

folder = tempfile.mkdtemp()
path = os.path.join(folder, "names.txt")

# Always give encoding= when reading or writing text files
with open(path, "w", encoding="utf-8") as f:
    f.write("নুসরাত\nArif\nতানিয়া\n")

with open(path, encoding="utf-8") as f:
    print(f.read().split())

print("file size:", os.path.getsize(path), "bytes")

# Binary mode gives bytes, not str
with open(path, "rb") as f:
    print(f.read(9))

# bytes and bytearray
b = bytes([72, 105, 33])
print(b, b.decode())
ba = bytearray(b"cat")
ba[0] = ord("b")
print(ba)

# Two strings can look the same but differ: composed vs decomposed letters
s1 = "café"                       # é as one character
s2 = "cafe\u0301"           # e + combining accent
print(s1 == s2, len(s1), len(s2))
n1 = unicodedata.normalize("NFC", s1)
n2 = unicodedata.normalize("NFC", s2)
print("after NFC:", n1 == n2)
print(unicodedata.name("৫"), "->", int("৫"))   # Bangla digits are real digits

Output

['নুসরাত', 'Arif', 'তানিয়া']
file size: 46 bytes
b'\xe0\xa6\xa8\xe0\xa7\x81\xe0\xa6\xb8'
b'Hi!' Hi!
bytearray(b'bat')
False 4 5
after NFC: True
BENGALI DIGIT FIVE -> 5
  • Always pass encoding="utf-8" to open() for text files. Without it, Python uses the system default, which is different on some Windows computers, so a file may read correctly on one PC and not on another.
  • The file holds 17 characters plus 3 line breaks, but it takes 46 bytes on disk, because most of the letters are Bangla.
  • Opening a file with "rb" (read binary) gives bytes. Use binary mode for images, PDFs and other non-text files.
  • bytes cannot be changed. A bytearray can, so you can replace single bytes.
  • Some letters can be stored in two ways: “é” as one code point, or “e” plus a separate accent mark. They look the same but are not equal. unicodedata.normalize("NFC", s) turns both into the same form, which matters when you compare or search names.
  • Bangla digits are real digits to Python: int("৫") is 5.

str vs bytes

strbytes
HoldsCharacters (code points)Numbers 0–255
Written as"Dhaka"b"Dhaka"
Convert to the others.encode("utf-8")b.decode("utf-8")
Used forText in your programFiles, networks, hashing, images

A good rule: decode as soon as data comes in, work with str, and encode just before it goes out.

Common Mistakes

  1. Mixing types, as in "Hi " + b"there", which raises TypeError. Decode the bytes first.
  2. Leaving out encoding= when opening text files.
  3. Using len() to measure size in bytes. len(s) counts characters; use len(s.encode("utf-8")) for bytes.
  4. Hiding problems with errors="ignore", which silently loses data. Find the right encoding instead.

Practice Exercises

Exercise 1. How many bytes does "বাংলা" take in UTF-8? Check it with Python.

Show answer
word = "বাংলা"
print(len(word), len(word.encode("utf-8")))   # 5 15

The word is 5 code points (ব, া, ং, ল, া), and each takes 3 bytes.

Exercise 2. Convert the Bangla number string "২০২৬" into the integer 2026 and add 1.

Show answer
year = int("২০২৬")
print(year + 1)   # 2027

int() accepts digits from any script that Unicode marks as decimal digits.

Frequently Asked Questions

Is UTF-8 the same as Unicode?

No. Unicode is the list of characters and their numbers. UTF-8 is one way of storing those numbers as bytes. UTF-16 and UTF-32 are other ways. UTF-8 is the most widely used.

My CSV file from Excel shows strange characters. What should I do?

Try opening it with encoding="utf-8-sig", which also removes the hidden marker some programs add at the start. If that fails, the file may use an older Windows encoding such as cp1252.

Summary

  • str holds text; bytes holds raw numbers from 0 to 255.
  • encode turns text into bytes; decode turns bytes into text.
  • Use UTF-8, and always give encoding="utf-8" for text files.
  • Normalize text with unicodedata before comparing.

Next: Python hashlib and secrets.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *