The prefix does the work
f"{name} scored {score}"
The f before the quote is what turns braces into slots. Without it you get the literal characters. Inside the braces goes any expression: a variable, a method call, arithmetic. The expression is evaluated at that point and its result is inserted into the string.
That is the whole idea, and it is why f-strings replaced every older formatting style. The value appears in the source where it appears in the output. Concatenation with + scatters the sentence across quotes and plus signs. The older % formatting and .format() push the values to the end of the line, away from the slots they fill. Both of those styles force you to count positions and match them up mentally. F-strings put the value right where it belongs.
Before f-strings arrived in Python 3.6, the standard approach was .format(). You would write "{} scored {}".format(name, score) or "{name} scored {score}".format(name=name, score=score). The intent is the same, but the reading order is broken. Your eye starts at the template, then jumps to the end to find the values, then jumps back to figure out which value goes where. F-strings fix that by placing the expression inline.
A format spec after a colon inside the braces controls width, alignment, decimal places, and type. f"{price:.2f}" prints two decimal places. f"{label:<20}" pads to twenty characters, left-aligned. These specs follow the same mini-language that .format() uses, so any format code you already know works inside an f-string too.
F-strings are also faster than .format() and % because Python compiles them into direct operations rather than parsing a template at run time. For most programs the speed difference is invisible, but it means there is no performance reason to prefer the older styles.
This page walks through the basic syntax, format specs for numbers and alignment, multiline f-strings, and the common mistakes that trip up beginners the first time they use braces inside a string.
After a colon comes a compact language for presentation:
:.2f — two decimal places:, — thousands separators:>8 — right-align in eight columns. < left, ^ centre:03d — pad to three digits with zeros:.1% — show as a percentage with one decimal
They combine: {price:>10.2f} right-aligns in ten columns with two decimals. That is how you get a table whose numbers line up without counting spaces by hand.
f"{value:.2f}" changes how the number is displayed. The variable is untouched, still carrying each digit it had. This matters when you print a rounded figure and then keep finding with the first. The printed total and the found total can differ. The program isn't wrong. The display was never the value.
The debugging shortcut
f"{total = }"
prints total = 42 — the formula and its value. It works for any formula. f"{len(items) = }" prints both the call and its result. It's the fastest way to instrument a function. It drops the classic mistake of printing a label that no longer matches the variable beside it.
Which to use
Use f-strings. % formatting and .format() still work and you'll meet them in older code. They exist now mainly to be read, not written. The one place .format() still earns its keep is when the template is stored apart from the values. A message in a config file, say. Because an f-string is tested where it's written.
Alignment is where the format spec earns its keep. Left-align text, right-align numbers, and the columns line up what the data:
rows = [("apple", 3, 1.5), ("banana", 12, 0.25), ("cherry", 100, 12.0)]
print(f"{'item':<10}{'qty':>5}{'price':>10}")
for item, qty, price in rows:
print(f"{item:<10}{qty:>5}{price:>10.2f}")
< left, > right, ^ centre, and the number after it's the field width. Numbers right-aligned with a fixed number of decimals is the combination you will use most, because it puts the decimal points under each other.
Dates, and why the same syntax works
The spec after the colon is handed to the object being formatted, so types can define their own:
from datetime import datetime
now = datetime(2026, 8, 20, 14, 30)
print(f"{now:%d %B %Y}") # 20 August 2026
print(f"{now:%H:%M}") # 14:30
That isn't a special date feature of f-strings. It's datetime reading the spec it was given. The same mechanism is why :.2f means a thing to a float and nothing to a string.
Quotes inside the braces
Before Python 3.12 you couldn't reuse the outer quote character inside the formula:
f"{d['key']}" # fine: single inside double
f"{d["key"]}" # SyntaxError before 3.12, allowed after
Sticking to the older form costs nothing and works all over, which is the usual reason to keep doing it.
Escaping a brace
A literal brace is doubled:
print(f"{{not a placeholder}} but {2 + 2} is")
# {not a placeholder} but 4 is
This matters when you're making JSON, CSS or any of it else that uses braces, and it's the first thing to check when an f-string raises a confusing KeyError.
Why f-strings replaced everything before them
Python has had four ways to build a string with values in it, and the differences are about where the values sit scaled to the text.
Concatenation with + scatters the sentence across quotes and plus signs, and needs str() around any of it that isn't already a string. Percent formatting moves the values to the end. So Reading the sentence means jumping between the template and the tuple. str.format is the same shape with better syntax. An f-string puts each value just where it will appear in the output.
That single property is why the mistakes go away. You can't pass the args in the wrong order, because there's no separate arg list. You can't supply too few, because each slot holds its own formula. And you can read the line and know what it prints without looking anywhere else.
What belongs inside the braces
Any formula is legal. This Means a great deal is possible and rather less is wise. A variable, an field, a dict lookup, a short method call or a small math formula all read fine. A nested comprehension or a long if-based doesn't: by the time the reader has parsed it they've lost the sentence it was embedded in.
The rule that holds up is that an f-string should still read as a sentence with holes in it. When the hole is bigger than the sentence, find the value on the line above and give it a name.
One habit worth keeping: format at the edge, never in the middle. Keep full precision in your variables and apply :.2f only where the value is printed or written out. Rounding early and then continuing to find is how totals stop matching the numbers above them, and it's a truly common source of small, hard-to-explain discrepancies in reports.
A worked example: a receipt
Alignment, decimals and a total, using nothing but the format spec:
items = [("apple", 3, 1.5), ("banana", 12, 0.25)]
total = sum(q * p for _, q, p in items)
print(f"{'item':<10}{'qty':>5}{'each':>8}{'cost':>9}")
for name, qty, price in items:
print(f"{name:<10}{qty:>5}{price:>8.2f}{qty * price:>9.2f}")
print(f"{'total':<10}{'':>5}{'':>8}{total:>9.2f}")
item qty each cost
apple 3 1.50 4.50
banana 12 0.25 3.00
total 7.50
The header row uses the same widths as the data rows. This Is what keeps the labels over their columns — and it works because a string can take an alignment and a width just as a number can. {'':>8} is an empty string padded to eight, which is how the total line skips columns without counting spaces.
Text is left-aligned and numbers right-aligned. This Isn't a style preference: right-aligning numbers puts the decimal points under each other, and that is what makes a column of figures readable at a glance.
Note that total is found from the full-precision prices, not from the rounded strings. Formatting is applied only where the number is printed, which is the habit that stops a column of rounded values from failing to add up to the rounded total.
The three parts of a replacement field
All inside the braces follows one shape: {formula!conversion:format_spec}, and knowing the three slots shows a few things that or else look like separate features.
The formula is any Python formula, tested at that point.
The conversion is !r, !s or !a, applied before formatting. !r calls repr instead of str. This Is what puts quotes around a string and makes whitespace visible — invaluable in a debugging print, because ana and ana look the same without it.
The format spec is all after the colon, and it's handed to the object itself. That is why :.2f means a thing to a float, %d %B %Y means a thing to a datetime, and neither means any of it to the other.
The spec can hold its own braces. This Is how a width found at runtime gets in:
name = "ana"
w = 8
print(f"{name!r:>{w}}")
print(f"{3.14159:.{2}f}")
'ana'
3.14
Nesting one level is allowed and is the standard way to align a table whose column widths are found from the data rather than written into the source.
Numbers as people read them
A handful of specs cover almost each number a person will look at.
print(f"{1234567:,}")
print(f"{0.256:.1%}")
print(f"{5:+d}")
1,234,567
25.6%
+5
, inserts thousands separators, and _ does the same with underscores. % times by a hundred and appends the sign. This Is the correct way to show a proportion — writing f"{x * 100:.1f}%" does the same thing with one more place to make a mistake. + forces a sign on plus numbers, which matters when the number is a change rather than a quantity.
Two further ones are worth having. :>10,.2f mixes alignment, separators and decimals, which is the full treatment for a money column. And :g chooses between fixed and scientific form based on magnitude. This Is handy when the range of values is unknown and awful when it isn't, because the column stops lining up.
For money in detail, note that floats aren't decimals. The formatting is honest about what it was given. If the math used floats, the rounding error was already there before the format spec saw it.
An f-string is a presentation choice, and presentation choices are worth keeping in one layer rather than scattered through the code that does the work.
The symptom of getting this wrong is a function that returns a string where it should return a number. def total(items) -> str that hands back "£7.50" looks convenient at the call site and has thrown away all else you might do with the value: adding it to another total, checking it, storing it, converting the currency. The caller who needs the number now has to parse the string back, and the parse will eventually meet a thousands separator.
Keep values as values, and format at the point of output. A reporting function takes numbers and makes the string. The math returns numbers. This is the same boundary arg as converting input at the edge, run in the opposite direction: parse on the way in, find in real types, format on the way out.
The second habit is to keep the template near the output rather than near the data. A dict of format specs per column, applied in the printing loop, is easy to change when the report changes. Specs scattered through the functions that found each figure aren't.
There's one honest exception: log messages and error text, where the string *is* the output and there's nothing downstream to preserve precision for. Even there, prefer logging.info("total %s", total) over an f-string, because the logger can then skip the formatting fully when the message is filtered out.
Questions people ask about f-strings and Formatting
Can I use an f-string for a template stored elsewhere? No, it is tested where it's written. str.format on a stored template is the tool for that.
Is an f-string faster than concatenation? Yes, often noticeably, because it doesn't build mid strings.
How do I put a quote inside? Use the other quote character, or — from Python 3.12 — the same one.
Can I have a backslash inside the braces? Not before Python 3.12. Find the value on the line above instead.
What does f"{x=}" do? Prints the formula text, an equals sign, and the value's repr. It's the fastest debugging print there's.
Do f-strings work with multi-line strings? Yes, prefix a triple-quoted string with f and the braces work throughout.
Is it safe to put user input in one? For output, yes. Never build SQL or shell commands this way. Use params, or the injection is on you.
Why does my f-string print braces truly? Because you doubled them, or because the f prefix is missing. Without the prefix the braces are plain characters.
Can I format a value whose width I only know at runtime? Yes, nest a field in the spec: f"{value:>{width}}".
What is the difference between !s and no conversion? Nothing, — str is the default. !r is the one worth typing.
How do I show a number rounded but keep full precision? Format only where you print. The variable is never changed by a format spec, so the math that follows still uses each digit it had.
Can I align text and numbers in the same column? Yes, and it often reads badly. Give the header the same alignment as the data if you want them to line up, or left-align both.
f-strings and Formatting: recap in one screen
- The
f prefix turns braces into slots holding any formula, tested where it appears in the sentence. - After the colon is a spec handed to the object:
.2f, ,, >8, % and %d %B %Y all work this way. !r shows the repr. This Is how you see quoting and stray whitespace.- Formatting changes the display, never the value. Format at the edge and keep full precision in the math.
f"{value=}" prints the formula and its value together.