1.2.13 · D3Introduction to Programming (Python)

Worked examples — f-strings — embedding expressions

2,522 words11 min readBack to topic

See the parent for the core rule: f-strings — embedding expressions.


The scenario matrix

Before any example, let's map the whole territory. An f-string has exactly three moving parts: the f prefix, the text outside braces, and the expression (plus optional format spec) inside braces. Every scenario is just a different thing living in one of those slots.

# Case class What varies Example we hit it with
A Plain variable simplest possible braces Ex 1
B Arithmetic / full expression operators inside braces Ex 2
C Calls & indexing .method(), [i] inside braces Ex 3
D Format spec after : — floats rounding, decimals Ex 4
E Format spec — padding & alignment width, fill, <^> Ex 5
F Degenerate / empty inputs empty string, zero, None Ex 6
G Literal braces (escaping) you WANT a { in output Ex 7
H The = debug form self-documenting output Ex 8
I Real-world word problem receipt / units Ex 9
J Exam-style twist evaluation order + nesting Ex 10

The chalkboard figure below shows how the interpreter physically walks a string and lands in each of these slots.

Figure — f-strings — embedding expressions

Now every cell, one at a time.


The worked examples


Recall checkpoint

Recall Answers

Empty brackets [] ::: str("") is genuinely empty text. 2.7 ::: .1f rounds to nearest, .67….7. ***42*** ::: fill *, centre ^, width 8. 7 ::: -1 is the last item of the sorted list [1,2,4,7]. The expression's source text and an = ::: e.g. x=9 for debugging.


Connections

  • f-strings — embedding expressions — the parent rule these examples exercise.
  • Format specification mini-language — everything after the : in Ex 4, 5, 9, 10.
  • str() and type conversion — why None, 0, "" all have safe string forms (Ex 6).
  • str.format() method — the older {} sibling with the same spec grammar.
  • Variables and scope — braces evaluate in the current scope (Ex 1).
  • print() function — the consumer of every line above.

How the matrix maps to slots

f-string

f prefix slot

literal text slot

brace field slot

expression before colon

spec after colon

Cell A plain var

Cell B arithmetic

Cell C calls index

Cell F empty zero None

Cell H debug equals

Cell D float round

Cell E pad align

Cell I receipt columns

Cell J nested spec

Cell G double brace escape