liveBook · Manning

F-string

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

An f-string is a Python string literal that evaluates expressions enclosed in braces and inserts their values into the resulting string.

An f-string is a Python string literal that puts variables or code directly inside curly-brace placeholders. Python evaluates each expression and inserts its value into the resulting string. section 2.1.12 section 2.5

A readable formatted phrase

With article = 'an' and word = 'octopus', print(f'Ahoy, Captain, {article} {word} off the larboard bow!') produces: Ahoy, Captain, an octopus off the larboard bow! Compared with str.format(), the variables stay beside their placeholders, so the expression is easier to read. section 2.1.12 section 2.3.4

Use f-strings to:

  • Build output from values chosen by a program, such as an article selected for a word. section 2.1.13
  • Control displayed widths with printf-style formatting options, such as {lines:8}. section 6.3.2 section 6.5
  • Combine computed expressions with fixed text, such as joined adjectives and a randomly selected noun. section 9.3.6
>>> adjs = ', '.join(random.sample(adjectives, k=3))
>>> print(f'You {adjs} {random.choice(nouns)}!')
You heedless, thin-faced, gross recreant!

A runnable example combines a joined list of adjectives and a randomly selected noun inside an f-string. section 9.3.6

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains placeholders, expression interpolation, readability, and width formatting, but does not descend into implementation internals.
Examples
Demonstrates nautical phrases, file-count columns, picnic output, and randomly generated insults.
What it assumes
Assumes basic variables and strings, then reinforces placeholders, indexing, joining, loops, and formatted printing through examples.
What you can do after
Apply f-strings to generate readable output containing variables, expressions, and controlled-width values.
How it connects
Connects f-strings with string literals, expressions, variables, str.format(), string joining, loops, and formatted output.

Also explained in

Compare how 4 books explain f-string →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.