Foundations · Lesson 3 of 18 · 18 min
Strings and text
Unicode, formatting, and the immutability of str.
- Treat str as an immutable Unicode sequence
- Format with f-strings
- Split, join, and slice without copying traps
A string is a sequence of Unicode code points
Python 3's `str` is Unicode. There is no 'character encoding' inside a string — encoding appears when you convert to `bytes` for the outside world (files, sockets, HTTP). `s.encode('utf-8')` produces bytes; `b.decode('utf-8')` produces a string.
Strings are immutable sequences. `s[0] = 'A'` is illegal. Methods like `replace` and `upper` return new strings. That is why building a string with `s += chunk` in a loop can be costly: each step copies. Prefer `''.join(parts)` when the piece count is large.
s = "PyForge"
print(s[0], s[-1], s[2:5])
print(s[::-1])
parts = ["learn", "python", "deeply"]
print(" · ".join(parts))
raw = "café"
print(raw.encode("utf-8"))
print(list(raw))f-strings are the default formatter
f-strings evaluate expressions inside braces: `f'{name} scored {score:.1f}'`. Debug printing can use `f'{score=}'`, which prints the expression and its value. Format specs after a colon control width, alignment, padding, and precision.
`str.format` and `%` still exist. Use them when the template is a separate string (translations, user-supplied patterns). For ordinary code, f-strings are clearer and faster.
name = "Ada"
score = 18.75
print(f"{name} scored {score:.1f}")
print(f"{score=}")
print(f"{name:>10}")
print(f"{42:08b}")
print(f"{1000000:,}")Check yourself
Quiz
1.What does `'ab' + 'cd'` produce?
2.Best way to assemble many pieces into one string?
3.What is the type of `'hi'.encode('utf-8')`?
Practice
Exercise
Write `slug(text)` that lowercases, splits on whitespace, and joins with hyphens. Strip extra spaces. Example: 'Hello PyForge World' → 'hello-pyforge-world'.
Tutor
Ask a question about this lesson. Answers are generated on demand and capped so the session stays focused.