liveBook · Manning

F-string

As explained in Python Workout, Second Edition

An f-string is a Python string literal that evaluates embedded expressions and formats their values into the resulting string.

Use an f-string when output must combine text with values such as numbers or variables. Prefix the string with f and place expressions inside curly braces: f'Hello, {name}'. Python evaluates each embedded expression and inserts its value. section 2.5 section 2.3

Choose f-strings over older formatting approaches when you need readable, expression-driven output:

  • Avoid concatenating strings and integers with +; place the number directly inside the expression braces. section 2.5
  • Evaluate expressions inside braces, including arithmetic and method calls, such as {x*2} or {y.capitalize()}. section 2.5
  • Use formatting specifications after a colon inside braces when values need alignment, as in {first:#<10}. section 2.5
name = 'world'
x = 100
y = 'abcd'
f'x * 2 = {x*2}, and y.capitalize() is {y.capitalize()}'

Compare direct variable interpolation with arithmetic and method evaluation in one executable example. section 2.5

name = 'world'
first = 'Reuven'
last = 'Lerner'
f'Hello, {first:#<10} {last:#>10}'     #1

Inspect alignment formatting by applying fill characters and width specifications to two values. section 2.5

How Python Workout, Second Edition covers it

How deep it goes
Defines interpolation, expression evaluation, and formatting specifications while contrasting older formatting methods.
Examples
Uses greeting output, arithmetic, capitalization, mixed numeric output, and aligned names as examples.
What it assumes
Assumes familiarity with variables, strings, numeric values, expressions, and method calls.
What you can do after
Apply it via Python f-string syntax to produce formatted output without separately passing formatting arguments.
How it connects
Connects string literals with expressions, string concatenation, the percent operator, and str.format.

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 Python Workout, Second Edition. The section links point to the parts of the book it draws on.