Strings & f-strings
Lesson 4 of 7 · View course roadmap
Learn the idea
Strings are sequences of characters. You can combine, repeat, measure and transform them:
"py" + "thon"— concatenation →"python"len(s)— lengths.upper(),s.lower(),s.strip(),s.replace(a, b)— transformationss[0]— first character (indexes start at 0!),s[-1]— last
The modern way to build strings is the f-string — put f before the quote and drop variables inside {}:
f-strings can hold any expression: f"{price * 2:.2f}" even formats to 2 decimal places. Master f-strings early — you will use them in every program you ever write.
Where you'll use this
f-strings are everywhere in production Python: log messages, SQL parameters, API URLs, email templates. Since Python 3.6 they've replaced every older formatting style in new code.
Common mistakes
- Strings are immutable:
s[0] = "H"is a TypeError. Methods like.upper()return a new string —s.upper()alone does nothing unless you assign it. - Off-by-one indexing: the first character is
s[0], ands[len(s)]is an IndexError. - Forgetting the
fprefix and printing literal braces:"{name}"vsf"{name}".
Pro tip
f-strings have a debug shorthand: f"{price=}" prints price=19.99 — name and value. Format specs go after a colon: f"{total:.2f}" (2 decimals), f"{n:,}" (thousands separators).
Watch how it runs — line by line
Press play to watch Python execute this code, one line at a time.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +25 XP
Given the variables in the starter code, use an f-string to print exactly: Alan has completed 5 courses
Alan has completed 5 courses
f"{student} has completed {courses} courses"
student = "Alan"
courses = 5
print(f"{student} has completed {courses} courses")
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.