Strings, Part 2: Encoding, Performance and Patterns
After this lesson, you will be able to:
- Explain what a character costs in memory, and what UTF-8 does about it
- Read and fix a UnicodeDecodeError instead of guessing at it
- Say why concatenating in a loop is slow, and use join instead
- Recognise where a regular expression is the right tool, and know that a later lesson teaches it
#String Encoding: Unicode and UTF-8
# ord() gives the code point of a character
print(ord('A')) # 65
print(ord('a')) # 97
print(ord('0')) # 48
print(ord(' ')) # 32
print(ord('€')) # 8364
print(ord('中')) # 20013
print(ord('😀')) # 128512
# chr() converts a code point back to a character
print(chr(65)) # 'A'
print(chr(97)) # 'a'
print(chr(8364)) # '€'
print(chr(128512)) # '😀'
# Strings ARE Unicode -- you can include any character
greeting = "Привет мир" # Russian
print(greeting)
print(len(greeting)) # 10 (characters, not bytes)
# Unicode escapes in string literals
print("\u0041") # 'A' (4-hex-digit Unicode escape)
print("\U0001F600") # '😀' (8-hex-digit for codepoints > 0xFFFF)
print("\N{SNOWMAN}") # '☃' (Unicode name)# UTF-8 encoding -- bytes per character
import sys
chars = ['A', 'é', '中', '😀']
for char in chars:
encoded = char.encode('utf-8')
print(f"{char!r:5} code point: {ord(char):7} UTF-8 bytes: {len(encoded)} hex: {encoded.hex()}")
# 'A' code point: 65 UTF-8 bytes: 1 hex: 41
# 'é' code point: 233 UTF-8 bytes: 2 hex: c3a9
# '中' code point: 20013 UTF-8 bytes: 3 hex: e4b8ad
# '😀' code point: 128512 UTF-8 bytes: 4 hex: f09f9880
# This is why len(string) != len(bytes) for non-ASCII
text = "Hello, 中文!"
print(f"len(str): {len(text)}") # 10 characters
print(f"len(bytes): {len(text.encode())}") # 14 bytes (中 and 文 are 3 bytes each)`'Hello, 中文!'` has len 10 as a string and 14 as bytes. Which number does a database column declared VARCHAR(12) care about?
# Reading files -- always specify encoding
with open("data.txt", "w", encoding="utf-8") as f:
f.write("Hello, 中文! Привет!")
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content) # correct
# What happens without encoding on Windows (may default to cp1252)
# You get: UnicodeDecodeError or garbage characters
# ALWAYS specify encoding="utf-8" when reading/writing text files
# API responses: decode bytes to str
import json
json_bytes = b'{"name": "Alice", "score": 95}'
text = json_bytes.decode("utf-8")
data = json.loads(text)
print(data["name"]) # "Alice"#String Performance: Why Concatenation in Loops is Dangerous
# THE WRONG WAY -- O(n^2) string concatenation
import time
words = ["word"] * 10000
# Method 1: += in a loop
start = time.perf_counter()
result = ""
for word in words:
result += word + " "
t1 = time.perf_counter() - start
# Method 2: join (correct way)
start = time.perf_counter()
result = " ".join(words)
t2 = time.perf_counter() - start
print(f"Loop += : {t1*1000:.3f} ms")
print(f"join() : {t2*1000:.3f} ms")
print(f"join is {t1/t2:.0f}x faster")
# the ratio varies by machine and Python version; run it to see yours# Building strings the CORRECT way
# Pattern 1: collect then join
parts = []
for i in range(1000):
parts.append(f"item_{i}")
result = ", ".join(parts)
# Pattern 2: use a list comprehension then join (even cleaner)
result = ", ".join(f"item_{i}" for i in range(1000))
# Pattern 3: for simple cases, f-strings with io.StringIO
from io import StringIO
buf = StringIO()
for i in range(1000):
buf.write(f"item_{i}\n")
result = buf.getvalue()
# Building HTML/CSV/SQL -- always use join or specialized libraries
headers = ["id", "name", "score"]
csv_header = ",".join(headers)
print(csv_header) # "id,name,score"
rows = [[1, "Alice", 95], [2, "Bob", 78]]
csv_rows = [",".join(str(cell) for cell in row) for row in rows]
csv_output = "\n".join([csv_header] + csv_rows)
print(csv_output)result += word in a loop is O(n²) while ''.join(parts) is O(n). What does += actually do that costs so much?
#Regular Expressions: Pattern Matching in Text
re module matches against any string. It is a small language of its own, so the full treatment is in the lesson on regular expressions later in the course. Until then, the string methods from these two lessons carry you a long way.#Code Playground: Text Processing Pipeline
Tests: Run to see the text pipeline in action. Then solve each challenge!
#String Processing: Real Patterns You'll Use
These are the string jobs that come up again and again — cleaning up messy input, building a message from parts, and pulling a value out of text somebody else formatted.
# ── 1. Clean up messy input ──────────────────────────────────────────
def clean_text(text: str) -> str:
"""Tidy text that a human typed."""
text = text.strip() # remove leading/trailing whitespace
text = " ".join(text.split()) # collapse multiple spaces to one
text = text.lower() # ignore capitalisation
return text
print(clean_text(" Hello THERE\n\n ")) # "hello there"
# ── 2. Build a message from parts with f-strings ─────────────────────
def build_receipt(name: str, items: list[str], total: float) -> str:
"""Construct a receipt from a list of items."""
lines = "\n".join(f" {i+1}. {item}" for i, item in enumerate(items))
return f"""Receipt for {name}
{lines}
Total: {total:.2f}"""
print(build_receipt("Asha", ["Coffee", "Sandwich"], 8.50))
# ── 3. Pull a value out of text ──────────────────────────────────────
def extract_between(text: str, opener: str, closer: str) -> str:
"""Return whatever sits between the first opener and the next closer."""
if opener not in text:
return text.strip()
start = text.index(opener) + len(opener)
end = text.index(closer, start)
return text[start:end].strip()
log = "INFO [2026-03-04] User signed in"
print(extract_between(log, "[", "]")) # "2026-03-04"
# ── 4. Split text into words ─────────────────────────────────────────
def to_words(text: str) -> list[str]:
"""Split into words, dropping the punctuation stuck to them."""
return [word for word in (w.strip(".,!?;:\"'()[]{}") for w in text.lower().split()) if word]
text = "Reading, at its core, is pattern recognition!"
words = to_words(text)
# ['reading', 'at', 'its', 'core', 'is', 'pattern', 'recognition']
print(f"Word count: {len(words)}")#Key Takeaways
- A string is characters; a file is bytes —
encode()crosses from one to the other when you write,decode()crosses back when you read, and namingencoding="utf-8"explicitly is what stops the same code behaving differently on another machine. - UTF-8 uses a variable number of bytes per character — ASCII characters take one and everything else takes two to four, so
len("café")is 4 characters whilelen("café".encode("utf-8"))is 5 bytes. Anything that measures or slices the encoded form is working in different units. - Never build a string with
+=in a loop — strings are immutable, so every pass copies everything accumulated so far and the total work grows as the square of the input. Collect the pieces in a list and call"".join(parts)once, which is linear. - A regular expression describes the shape of the text — rather than fixed positions, so it survives input that shifts. The lesson on regular expressions teaches it in full.
- Write backslash-heavy text as raw strings —
r"C:\new\table"keeps backslashes literal, so the text you read is the text Python stores. - Real text work is a pipeline — read, decode, clean, split, match, join — each step one tool from these two lessons applied to the output of the last.
Why is 'result = "".join(parts)' faster than building a string with += in a loop?
This program encodes some text and then tries to print it in a sentence. It crashes because bytes and str are different types. Fix it so the greeting prints.
Greeting: café
Password strength checker
Write a function `strength(password)` that returns a score from 0 to 5. Add 1 point for each of: length >= 8, contains a lowercase letter, contains an uppercase letter, contains a digit, contains a special character from `!@#$%^&*`.
>>> strength("abc")
1
>>> strength("Abcdef12")
4
>>> strength("Abcdef12!")
5