Beginner   Chapter 35 · 25 min read · Module 3: Python Strings

f-Strings

Learning objectives
  • After this chapter you can write an f-string that inserts variables and expressions into text.
  • You can format numbers with decimals, thousands separators and percentages.
  • You can align and pad text using width, fill and alignment options.
  • You can use the = specifier and conversions such as !r for debugging.
  • You can avoid common f-string mistakes with quotes, braces and dictionary keys.

When a program talks to people it must build sentences from data: a name, a price, a score. Older ways of doing this joined many small pieces with plus signs or used percent codes. They work, but they are hard to read because the text and the values are far apart.

An f-string solves this. You put the letter f before the opening quote and then write values directly inside curly braces. Python replaces each pair of braces with the value. The result reads almost like the final sentence, which makes the code easy to check.

In this chapter you will learn the basic form, how to place full expressions inside braces, and how to control the look of numbers and columns. F-strings were added in Python 3.6, so every modern Python has them. You will also meet the debugging helper = and a few small mistakes to avoid.

The basic f-string

An f-string is a string literal that starts with f or F right before the quote. Inside it, anything between { and } is treated as Python code. Python runs that code, turns the result into text and puts it in place. Because the work happens when the line runs, the braces always show the current value of a variable.

f-string: a string literal prefixed with f whose curly-brace fields are replaced by the values of Python expressions
Example 1: variables inside braces
name = "Asha"
age = 21
print(f"My name is {name} and I am {age} years old.")
print(f"Next year I will be {age + 1}.")
My name is Asha and I am 21 years old. Next year I will be 22.

Notice that age is a number, yet it appears inside the sentence without any conversion. An f-string calls str() style conversion for you. The second line shows that braces hold real expressions, not only names. You can do arithmetic, call functions, use methods or write a conditional expression, as long as the result can be shown as text.

Expressions, methods and function calls

Anything that is a valid expression works inside braces. This keeps small calculations next to the text that needs them. If the expression grows long, it is better to compute it first and put the result in a variable, because a short field is easier to read.

Example 2: expressions in braces
price = 49.5
qty = 4
item = "pen"
print(f"{qty} {item}s cost {price * qty}")
print(f"Upper: {item.upper()}, length: {len(item)}")
print(f"Status: {'cheap' if price < 50 else 'costly'}")
4 pens cost 198.0 Upper: PEN, length: 3 Status: cheap

Look at the last line. The text inside the braces uses single quotes while the outer string uses double quotes. Before Python 3.12 you could not reuse the same kind of quote inside the braces. Python 3.12 relaxed this rule, but using a different quote type is still the safest habit because it works in every version.

Format specifiers

After the expression you may add a colon and a format spec. The spec says how the value should look. For numbers, .2f means two digits after the decimal point, , adds thousands separators, and % multiplies by 100 and adds a percent sign. For text and numbers, a width such as 10 reserves that many characters, and <, > or ^ choose left, right or centre alignment.

SpecMeaningExample result
.2ftwo decimal places3.14
,thousands separator1,234,567
.1%percentage with one decimal12.5%
08.3fzero padded, width 80003.142
<8left align in width 8ab
>8right align in width 8 ab
^8centre in width 8 ab
bbinary integer101
Example 3: numbers and alignment
pi = 3.14159265
big = 1234567
ratio = 0.125
print(f"pi = {pi:.2f}")
print(f"big = {big:,}")
print(f"ratio = {ratio:.1%}")
print(f"[{'ab':<6}] [{'ab':>6}] [{'ab':^6}]")
print(f"[{'ab':*^6}]")
print(f"id = {7:03d}")
pi = 3.14 big = 1,234,567 ratio = 12.5% [ab ] [ ab] [ ab ] [**ab**] id = 007

In the last two prints you can see a fill character. Write the fill character before the alignment sign, as in *^6, and Python fills the empty space with it. The 03d spec means an integer, at least three characters wide, padded with zeros. These small specs are all you need to print neat tables of results.

Dynamic width and the debugging = sign

The width and precision can themselves come from variables if you nest braces inside the spec. This is useful when the width depends on the data. Python 3.8 added the = specifier: writing {x=} prints the expression text, an equals sign and its value. It is perfect for quick debugging because you do not have to type the name twice.

Example 4: nested fields, = and !r
width = 8
precision = 3
value = 2.718281828
print(f"[{value:{width}.{precision}f}]")
x = 10
y = 4
print(f"{x=} {y=} {x * y=}")
text = "hi"
print(f"{text!r} and {text!s}")
[ 2.718] x=10 y=4 x * y=40 'hi' and hi

The !r conversion shows the repr() of the value, which for a string includes the quotes. This helps when you need to see hidden details such as spaces. !s uses str() and !a uses ascii(). Most of the time you do not need a conversion, but !r is a great debugging friend.

Braces, quotes and multiline f-strings

If you need a real curly brace in the output, double it: {{ gives { and }} gives }. Backslashes inside the expression part were not allowed before Python 3.12, so keep such values in variables if your code must run on older versions. F-strings also work with triple quotes for several lines, and you can use implicit joining of neighbouring string pieces to build long messages cleanly.

Example 5: literal braces and a report
scores = {"math": 91, "art": 78}
print(f"{{math}} = {scores['math']}")
for subject, mark in scores.items():
    print(f"{subject:<6}|{mark:>4}")
report = f"""Total: {sum(scores.values())}
Average: {sum(scores.values()) / len(scores):.1f}"""
print(report)
{math} = 91 math | 91 art | 78 Total: 169 Average: 84.5
An f-string is evaluated once, at the moment the line runs. If a variable changes later, text that was already built does not change.

When should you choose an f-string over other tools? Use it nearly always for building messages in running code, because it is the fastest and the clearest. Use str.format() or a template when the pattern must be stored separately from the values, for example in a settings file or a translation table, since an f-string must sit in the source code next to the variables it reads.

Python syntax

Syntax
f"text {expression}"
Syntax
f"{value:format_spec}"
Syntax
f"{value!r}"  # conversion
Syntax
f"{expression=}"  # debugging form

Real-world applications

  • Printing friendly messages, receipts and reports
  • Formatting money, percentages and dates in tables
  • Quick debugging output with the = specifier
  • Building file names, URLs and log lines from variables

Common mistakes

Mistake: Forgetting the f prefix, so the braces are printed as plain text
Fix: Put f directly before the opening quote and check the output once.
Mistake: Using the same quote type inside the braces on Python older than 3.12
Fix: Use a different quote type inside the braces, such as single quotes inside a double-quoted f-string.
Mistake: Writing a single { or } that should appear in the output
Fix: Double the brace as {{ or }}.
Mistake: Putting very long calculations inside the braces
Fix: Compute the value first, store it in a variable and show the variable.
Mistake: Trying to use an f-string as a reusable template stored in a variable defined earlier
Fix: Use str.format() for templates, because an f-string reads variables at the moment the line runs.

Important tips

  • Use .2f for money and :, for large numbers.
  • Use {x=} while debugging to print names and values together.
  • Align columns with a width and < or > in the spec.
  • Keep expressions short and readable.

Key points summary

  • An f-string starts with f and uses {} fields.
  • Fields hold full Python expressions.
  • A colon after the expression starts the format spec.
  • Use {{ and }} for literal braces.
  • The = specifier needs Python 3.8 or newer.

Exam and interview points

  • The f prefix is case insensitive: f and F both work.
  • Format spec order is fill, align, sign, width, grouping, precision, type.
  • {x!r} calls repr and {x!s} calls str.
  • F-strings are evaluated at runtime, not at definition of the variables.

Quick revision

  • f"...{x}..." inserts the value of x.
  • {x:.2f} gives two decimals.
  • {x:>8} right aligns in width 8.
  • {{ }} prints literal braces.
  • {x=} prints name and value.

Frequently asked questions

Which Python version do I need for f-strings?

Python 3.6 or newer. The = specifier needs 3.8 and the relaxed quote rules need 3.12.

Are f-strings faster than format()?

Usually yes. They are evaluated directly in the running code, so they are often a little faster and always shorter.

Can I put a dictionary lookup inside an f-string?

Yes, but use different quotes for the key, for example f"{d['key']}".

Can I reuse one f-string with different values?

Not directly, because it is evaluated once. Wrap it in a function or use str.format() for templates.

How do I print a percent sign?

Just write it. Percent has no special meaning in f-strings unless it is used as a format spec after a colon.

Practise this chapter

22 practice questions Take the chapter quiz

Related chapters