1.2.13Introduction to Programming (Python)

f-strings — embedding expressions

1,762 words8 min readdifficulty · medium2 backlinks

WHY do f-strings exist?

Before f-strings, building a string from variables was clumsy:

name = "Ada"
age = 36
# Old way 1: concatenation — must manually convert ints to str
msg = "Hi " + name + ", you are " + str(age)
# Old way 2: .format() — placeholders separated from values
msg = "Hi {}, you are {}".format(name, age)

Both are error-prone: you forget str(), you mismatch the order of {} and arguments, and you read the values far away from where they're used.

WHAT is an f-string?

f"text {expression} more text"
  • The f prefix turns on the magic.
  • Everything outside braces is literal text.
  • Everything inside braces is code that runs.

HOW does evaluation work? (derive from first principles)

Think of the interpreter scanning the string once, left to right:

  1. Copy literal characters straight to the output.
  2. On hitting {, read until the matching }. That chunk is parsed and executed as a Python expression in the current scope.
  3. The result is converted to text (default: like str(...)) and appended.
  4. Continue until the string ends.

So the braces hold any expression — variables, arithmetic, function calls, method calls, indexing — not just plain variable names.

Figure — f-strings — embedding expressions

Worked examples

Common mistakes

Recall Feynman: explain to a 12-year-old

Imagine a fill-in-the-blank story: "My dog is ___ years old." A normal Python string is the story with the blank left empty — it just prints ___. An f-string is the story where you write a little instruction inside the blank, like {2 + 3}, and the computer secretly solves it and writes 5 in the gap before showing you the sentence. The f is the magic stamp that says "hey, fill in the blanks!"

Recall checkpoint


What prefix turns a string into an f-string?
The letter f (or F) placed immediately before the opening quote, e.g. f"...".
Inside an f-string, what can go between { }?
Any Python expression (variable, arithmetic, function/method call, indexing) — anything that evaluates to a value.
How do you embed 7 + 5 and show its result in an f-string?
f"{7 + 5}"12 (the expression is evaluated, then converted to text).
How do you print a literal { and } inside an f-string?
Double them: {{ prints { and }} prints }.
What does the part after a colon mean, as in f"{pi:.2f}"?
It's a format specification; .2f formats the value as a float with 2 decimal places.
What does f"{x=}" do (Python 3.8+)?
Prints both the expression text and its value, e.g. x=9 — handy for debugging.
What's the conceptual substitution rule of an f-string?
Each {expr} is replaced by format(expr, spec) (defaulting to str(expr)), and all literal/converted pieces are joined in order.
Why does print("Hi {name}") print {name} literally?
Without the f prefix it's an ordinary string, so braces are just characters, not expression markers.
What does f"{42:05d}" produce and why?
0004205d pads the integer to width 5 with leading zeros.

Connections

  • Strings — literals and quotes — f-strings are a kind of string literal.
  • str() and type conversion — braces implicitly call str()/format().
  • str.format() method — the older sibling using {} placeholders.
  • Format specification mini-language — what lives after the :.
  • Variables and scope — expressions in braces use the current scope.
  • print() function — most common consumer of f-strings.

Concept Map

error prone

motivates

prefixed with

uses

activates

contain

includes

scans

replaces expr with

joined with

forms

benefit

Old ways concat and format

Clumsy string building

f-string

f or F prefix

Curly braces { }

Expression evaluation

Any Python expression

Vars, arithmetic, calls, indexing

Left-to-right substitution

str of expr result

Literal text outside braces

Value sits where it appears

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, f-string ka matlab simple hai: jab string ke aage f lagate ho, to us string ke andar curly braces { } ke beech jo bhi likhoge wo Python expression ki tarah chal jaata hai. Matlab f"Hello {name}" likhne par Python name ki value uthaake wahin chipka dega. Pehle log "Hi " + name + str(age) aise jod-jod ke likhte the — bahut galti hoti thi, str() lagana bhool jaate the. f-string ne yeh sab simple kar diya: value waheen likho jahan dikhani hai.

Braces ke andar sirf variable hi nahi, koi bhi expression aa sakta hai — {a + b}, {word.upper()}, {price[0]} sab chalega. Python pehle us expression ko solve karta hai, phir uska text bana ke string mein daal deta hai. Yaad rakho: f for FILLf Python ko bolta hai ki blanks bhar do.

Colon : ke baad jo aata hai wo formatting hai — jaise {pi:.2f} matlab do decimal tak dikhao, {price:,} matlab thousands mein comma lagao, {42:05d} matlab paanch digit tak zero se bhar do. Isko aise samjho: colon ke baad value ko "costume" pehnate ho.

Do common galtiyan: (1) f lagana bhool gaye to {name} waise ka waisa print ho jaayega — magic off rahega. (2) Agar literal { chahiye to double karo {{. Bas itna dhyaan rakho aur f-strings tumhare code ko clean aur readable bana denge.

Go deeper — visual, from zero

Test yourself — Introduction to Programming (Python)

Connections