F-strings are made for formatting output. They are the fastest and clearest way to build aligned, precise text in Python, and they replaced two older styles that were harder to read and easier to get wrong. They arrived in Python 3.6 and have improved in every release since. The most useful change came in 3.12, which allowed the same quote character inside an expression and f-strings that run over several lines. The format specification is worth learning properly, because that is where f-strings stop being convenient and start being powerful.
The previous lesson in this module covered "Type Conversion (Casting) Without Bugs", and this lesson is the last one in the Python Data Types and Variables module.
What is an f-string?
Put the letter f in front of a string, and any expression inside braces is worked out and turned into text. That is the whole idea. Everything else is about how the result is laid out on the screen.
name = 'Ada'
score = 92.4567
print(f'Hello, {name}!')
print(f'{name} scored {score} points.')
print(f'{name!r} is a {type(name).__name__}')
print(f'{name=}')
print(f'{score=:.2f}')
print(f'{{literal braces}} next to {name}')
Four of those lines have extra features. The !r suffix applies the repr() conversion, so quotes appear around a string, which helps when you are debugging. The = specifier prints the expression and its value together, and it is a debugging aid that you will use all the time. Doubling the braces prints literal braces, which matters when your text contains JSON or CSS. And f'{score=:.2f}' puts the two together, giving you score=92.46 without repeating the variable name.
The older styles still exist. '{}'.format(value) uses numbered or named placeholders, and '%s' % value is the printf style that you met in an earlier lesson. Both of them are harder to read and slower to run, because f-strings are compiled into a faster set of instructions instead of being parsed while the program runs. Use them only when you are reading old code.
The format specification itself follows a documented shape. In order it takes a fill character, an alignment, a sign option, a width, a thousands separator, a precision, and a type character. Filling and alignment are the parts that you will use most, because they turn a list of values into a readable table.
How do you control alignment and width?
After the expression comes a colon, and after the colon comes the specification. The most useful part of it is a width with an alignment character: < for left, > for right, and ^ for centre. You can also give a fill character and a total width.
rows = [('keyboard', 129.99), ('monitor', 249.5), ('cable', 9.99)]
print(f'{"item":<12}{"price":>10}')
print('-' * 22)
for item, price in rows:
print(f'{item:<12}{price:>10.2f}')
print()
print(f'{"centre":^22}')
print(f'{"right":>22}')
print(f'{"left":<22}')
print(f'{"filled":*^22}')
Two details make this practical. The width applies to the finished text, so {price:>10.2f} means "two decimal places, right aligned in ten characters". And the precision applies to numbers only. For a string, .2 means something completely different, so keep the two apart in your head.
How do you format numbers?
The type character at the end of the specification decides how the value is shown. A comma adds thousands separators, % turns a fraction into a percentage, and the letters b, o, x, and X give binary, octal, hexadecimal, and uppercase hexadecimal.
value = 1234567.891
print(f'{value:,.2f}')
print(f'{value:+.2f}')
print(f'{value:.3e}')
print(f'{value:.4g}')
print(f'{0.256:.1%}')
print(f'{255:b} {255:o} {255:x} {255:X}')
print(f'{42:>10,}')
The comma and the plus sign can be combined, and that is what makes signed money easy. The g format is worth knowing, because it switches between fixed and scientific notation depending on the size of the number. That is what you want in a report where the values run from pennies all the way to millions.
One caution: formatting is about how something looks, and not about the rounding itself. f'{value:,.2f}' rounds for the screen, but the float underneath does not change. Adding numbers that were only ever rounded for display is how rounding errors get into a total. Keep the precise values in the data and format them at the edge.
Which f-string tricks save you time?
Beyond the format specification there are a few more details worth knowing. Date and time objects understand their own format codes, and you can use them straight inside an f-string.
from datetime import date, datetime
payload = {'user': 'ada', 'roles': ['admin', 'dev']}
print(f'plain -> {payload}')
print(f'repr -> {payload!r}')
when = datetime(2026, 10, 27, 14, 30)
print(f'short -> {when:%Y-%m-%d %H:%M}')
print(f'long -> {when:%B %d, %Y}')
print(f'date -> {date(2026, 1, 5):%d %b %Y}')
Since Python 3.12, an f-string can run over several lines, and it can use the same quote character inside the expression as the one that surrounds the string. That removes a pile of old workarounds, such as saving a dictionary lookup in a variable first.
class Temperature:
"""A reading in Celsius that knows how to format itself."""
def __init__(self, celsius):
self.celsius = celsius
def __format__(self, spec):
if not spec:
spec = '.1f'
return f'{self.celsius:{spec}} C'
reading = Temperature(21.456)
print(f'{reading}')
print(f'{reading:.2f}')
name = 'Ada'
items = ['keyboard', 'monitor']
report = f'''
Report for {name}
Items: {", ".join(items)}
'''
print(report)
The __format__ method is how an object joins the f-string system. The built-in format() function calls it as well, so a class with that method can be formatted anywhere a number can be. You will meet the same idea in the standard library, where dates, decimals, and durations all provide their own formatting behaviour.
Your turn: build a receipt formatter
- Write a script with a list of
(item, quantity, unit_price)triples and print a receipt. Put the item name left aligned in 20 characters, the quantity right aligned in 4, and the line total right aligned in 10 with two decimal places. - Print a separator line of the right width, and then print a total line with an f-string that uses
=, so that it reads liketotal=57.48. - Add a column that shows each item's share of the bill, using the
%format. Make sure that the percentages line up in the same column as the prices. - Print the payment date with a
datetimeinside an f-string, in two formats:%Y-%m-%dand%d %B %Y. - Finally, give one of your own classes a
__format__method, and format it in an f-string with and without a specification. Check that the two outputs differ only in the number of decimal places.
Formatting quick reference
- Put expressions in braces inside a string that starts with
f. - After a colon comes the specification:
<,>, or^for alignment, then a width, then a precision for numbers, and then a type character. - Use
,for thousands separators,%for percentages, andb,o,xfor other bases. =prints the expression with its value, and!ror!spick the conversion.- Escape literal braces as
{{and}}, and remember that Python 3.12 allows the same quote inside an expression and f-strings over several lines.