Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Strings & f-strings

14 min 25 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 4 of 7 · View course roadmap
Step 1

Learn the idea

Strings are sequences of characters. You can combine, repeat, measure and transform them:

  • "py" + "thon" — concatenation → "python"
  • len(s) — length
  • s.upper(), s.lower(), s.strip(), s.replace(a, b) — transformations
  • s[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], and s[len(s)] is an IndexError.
  • Forgetting the f prefix and printing literal braces: "{name}" vs f"{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).

Step 2

Watch how it runs — line by line


        

Press play to watch Python execute this code, one line at a time.

Step 3

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 4

Pass the challenge +25 XP

Blank · autosaved

Given the variables in the starter code, use an f-string to print exactly: Alan has completed 5 courses

Target output
Alan has completed 5 courses
PYchallenge.py
Run your code to check it…
Step 5

Check your understanding

1. What does "hello"[1] return?
2. What does f"{2 + 3}" evaluate to?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path