Skip to content

Module 7 · Strings — topic 20 of 22

f-strings

f-strings put expressions directly inside string literals: f"{name} scored {marks:.1f}". Learn expressions, format specifiers, the = debugging form, quotes and braces inside f-strings, and multi-line f-strings.

Beginner 12 min read·Lesson 101 of 306 in Python Programming

Learning objectives

  • Embed variables and expressions in f-strings
  • Apply format specifiers inside f-strings
  • Use the {x=} form for quick debugging

Definition

f-strings put expressions directly inside string literals: f"{name} scored {marks:.1f}". Learn expressions, format specifiers, the = debugging form, quotes and braces inside f-strings, and multi-line f-strings.

Introduction

An f-string is a string literal prefixed with f. Anything inside curly braces is evaluated as a Python expression and its value is inserted into the text: f"{name} is {age} years old". It is the most readable way to build text from values.

Why it matters

f-strings keep the text and the values together in reading order, avoid str() conversions and + chains, and support the full formatting mini-language. They are the modern default for messages, reports and logs.

Detailed explanation

Readability is the main reason f-strings became the standard. In f"{name} owes {amount:.2f}" you read the sentence in order with the values in place, whereas "{} owes {:.2f}".format(name, amount) makes you match each pair of braces with an argument further along the line.

Any expression can go inside the braces: variables, arithmetic, method calls and function calls, such as f"{price * qty:.2f}" or f"{name.upper()}".

A format specifier follows a colon, exactly as with str.format(): f"{amount:,.2f}", f"{name:<10}", f"{ratio:.1%}".

Adding = after an expression prints both the expression and its value, which is handy while debugging: f"{total=}" gives total=450.

!r inside the braces uses the repr() form, which shows quotes around strings: f"{text!r}".

To show a literal brace, double it: f"{{braces}}".

Use a different quote type inside the braces than around the f-string in older Python versions, for example f"{data['name']}".

f-strings can be triple-quoted for multi-line templates, and an f prefix can be combined with r for raw f-strings (rf"...").

f-strings are evaluated when the line runs, using the current values of the variables.

Syntax

Python
f"{variable}"
f"{expression:specifier}"
f"{value=}"
f"{text!r}"
  • The f prefix enables expressions in braces.
  • Specifiers follow a colon.
  • = shows the expression and its value.

Code examples

Variables and expressions

Python
name, marks, max_marks = "Asha", 82, 100
print(f"{name} scored {marks}/{max_marks}")
print(f"Percentage: {marks / max_marks:.1%}")
print(f"Upper: {name.upper()}, letters: {len(name)}")
Output
Asha scored 82/100
Percentage: 82.0%
Upper: ASHA, letters: 4

Debugging and repr

Python
total = 450
item = "pen "
print(f"{total=}")
print(f"{item!r} has a trailing space")
print(f"{{literal braces}} and {total}")
Output
total=450
'pen ' has a trailing space
{literal braces} and 450

More examples

A formatted student report

Python
students = {"Asha": [82, 91, 78], "Ben": [67, 74, 59], "Chen": [95, 88, 92]}
print(f"{'Name':<6} {'Avg':>6} {'Best':>5} Result")
for name, marks in students.items():
avg = sum(marks) / len(marks)
result = "Distinction" if avg >= 85 else "Pass"
print(f"{name:<6} {avg:>6.2f} {max(marks):>5} {result}")
class_avg = sum(sum(m) for m in students.values()) / sum(len(m) for m in students.values())
print(f"{class_avg = :.1f}")
Output
Name      Avg  Best  Result
Asha    83.67    91  Pass
Ben     66.67    74  Pass
Chen    91.67    95  Distinction
class_avg = 80.7

Step-by-step explanation

  • The header uses literal strings inside braces only to apply the same alignment as the data columns.
  • {avg:>6.2f} right-aligns the average in 6 characters with 2 decimals.
  • A conditional expression chooses the result word, and max(marks) is computed inside the f-string.
  • {class_avg = :.1f} combines the debug = with a format specifier; the spaces around = are kept in the output.

Expected output

Running “A formatted student report” prints exactly:

TextOutput
Name Avg Best Result
Asha 83.67 91 Pass
Ben 66.67 74 Pass
Chen 91.67 95 Distinction
class_avg = 80.7

Practical applications

  • Logging messages are written as f-strings with values inline.
  • Web apps build notification text with f-strings.
  • Data scientists print formatted metrics such as f"{accuracy:.2%}".

Best practices

  • Use f-strings as the default way to build messages.
  • Keep expressions inside braces short; compute complex values first.
  • Use {value=} for quick debugging output.

Common mistakes

Forgetting the f prefix

Avoid

"Hello {name}"

Prefer

f"Hello {name}"

Without f, the braces are printed literally.

Putting a specifier outside the braces

Avoid

f"{price}:.2f"

Prefer

f"{price:.2f}"

The specifier must be inside the braces after a colon.

Key takeaways

  • f"...{expr}..." inserts expression values into text.
  • Specifiers after a colon format numbers and alignment.
  • {x=} shows the expression and value; double braces print literal braces.

Try it yourself

  1. 1
    Print a product name, quantity and total price (2 decimals) in one f-string.
  2. 2
    Use {x=} to debug three variables in a small calculation.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic