f-strings & String Formatting
Published by Brayan K
Almost every program eventually needs to weave data into text — a greeting with the user's name, a receipt with a price, a log line with a timestamp. f-strings are Python's clean, fast, and readable way to do exactly that.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
An f-string puts values into text
In Introduction to Python, print("Age: " + 25) stopped with a TypeError, because + won't join text and a number. An f-string is a string with the letter f just before the opening quote. Anything inside its curly braces is run as Python, turned into text and dropped into place, so a number needs no str():
name = "Ada"
age = 36
print("Hi " + name + ", you are " + str(age) + ".")
print(f"Hi {name}, you are {age}.")
# ✅ Expected output:
# Hi Ada, you are 36.
# Hi Ada, you are 36.Both lines print the same sentence, but the f-string reads like its output. Leave out the f and nothing goes wrong, which is the trouble: Python prints the braces as they are, with no error to warn you.
name = "Ada"
print("Hi {name}!")
print(f"Hi {name}!")
# ✅ Expected output:
# Hi {name}!
# Hi Ada!Any expression can go in the braces
The braces take any expression, not only a name: a sum, a function call, an item of a list, a value from a dictionary, a method call.
width = 4
height = 2.5
scores = [88, 92, 79]
user = {"name": "Ada", "plan": "Pro"}
print(f"Area: {width * height}")
print(f"Best: {max(scores)} of {len(scores)}")
print(f"First: {scores[0]}")
print(f"Plan: {user['plan']}")
print(f"Shout: {user['name'].upper()}")
# ✅ Expected output:
# Area: 10.0
# Best: 92 of 3
# First: 88
# Plan: Pro
# Shout: ADAThe area is 10.0, a float, because 2.5 is one. .upper() is one of the String Methods, which make new text from old.
The dictionary keys are in single quotes because the f-string itself is in double quotes. Python 3.12 and later also accept the same quotes inside the braces, but 3.11 and earlier stop with a SyntaxError, and the Run button on this site runs Python 3.11, so use the other kind. When an expression grows long, work it out on its own line first and put just the name in the braces.
A format spec controls how a value looks
After the value, a colon starts a format spec, {value:spec}, which says how the value should look:
total = 1299.5
ratio = 0.8734
visitors = 9500000
print(f"Total: {total:.2f}")
print(f"Share: {ratio:.1%}")
print(f"Visitors: {visitors:,}")
print(f"Revenue: {visitors * 0.1:,.2f}")
print(f"Order: {42:05}")
# ✅ Expected output:
# Total: 1299.50
# Share: 87.3%
# Visitors: 9,500,000
# Revenue: 950,000.00
# Order: 00042.2f shows two digits after the point. .1% multiplies by 100 and adds a percent sign, with one decimal. , puts a comma between the thousands, and goes before .2f when you want both. 05 pads with zeros to a width of 5. Dates have codes of their own after the colon, which Dates & Times (datetime) covers.
A spec changes only the text it makes. The number stays as it was:
price = 19.5
print(round(price, 2))
print(f"{price:.2f}")
print(price)
print(f"{2.675:.2f}")
print(f"{0.15:.0%}")
print(f"{15:.0%}")
# ✅ Expected output:
# 19.5
# 19.50
# 19.5
# 2.67
# 15%
# 1500%round() gives back a number, and a number doesn't keep a trailing zero, so only .2f shows 19.50, and printing price afterwards shows the variable didn't change. 2.675 shows as 2.67, not 2.68: the float nearest to 2.675 is a hair below it, and .2f rounds the number actually stored. For money that has to add up to the cent, Numbers: int, float, Decimal & Fraction has the Decimal type. And % multiplies by 100, so give it the fraction 0.15, not 15.
When the spec doesn't fit the value
Each spec is written for a kind of value: .2f, % and , are for numbers, and d only for whole numbers. Text that looks like a number isn't one. Here price holds the text "19.5", which is what input() gives you when someone types a price:
price = "19.5"
print(f"Total: {price:.2f}")
# ✅ Expected error:
# ValueError: Unknown format code 'f' for object of type 'str'Turn the text into a number first with float(), from Variables and Data Types:
price = "19.5"
print(f"Total: {float(price):.2f}")
# ✅ Expected output:
# Total: 19.50d fails the same way on a float, even one with nothing after the point, such as 10 / 2: use .0f, or int() first. The other common case is None, which is what a function gives back when it prints its answer instead of returning it, as Functions explains:
def add(a, b):
print(a + b)
total = add(2.5, 4)
print(f"Total: {total:.2f}")
# ✅ Expected output:
# 6.5
# ✅ Expected error:
# TypeError: unsupported format string passed to NoneType.__format__The function printed 6.5, then gave back None, which the spec can't format. Without the spec, the line would run and show the word None, which is easy to miss. The fix is a return in the function.
Width and alignment line up columns
A number after the colon is a width. Text sits on the left of its width and numbers on the right, unless you choose with < (left), > (right) or ^ (centre). A character just before that sign fills the gaps:
print(f"[{'tea':6}]")
print(f"[{42:6}]")
print(f"[{'tea':>6}]")
print(f"[{42:<6}]")
print(f"[{'tea':^7}]")
print(f"[{'tea':*^7}]")
print(f"[{'Wireless Mouse':6}]")
# ✅ Expected output:
# [tea ]
# [ 42]
# [ tea]
# [42 ]
# [ tea ]
# [**tea**]
# [Wireless Mouse]The width is a minimum. A longer value is never cut, so it pushes the rest of the line along, as Wireless Mouse does. Pick widths that fit the longest value and the lines form columns. The parts of a spec go in a fixed order: fill and alignment, width, comma, then the decimals and type, as in {cost:>8.2f}:
menu = {"Coffee": 3.5, "Sandwich": 6.25, "Tea": 2}
print(f"{'Item':<10}{'Price':>8}")
for name, cost in menu.items():
print(f"{name:<10}{cost:>8.2f}")
# ✅ Expected output:
# Item Price
# Coffee 3.50
# Sandwich 6.25
# Tea 2.00Printing a brace
Braces mean "run this", so a brace you want to see is written twice: {{ prints { and }} prints }.
size = 3
print(f"Sets are written like {{1, 2, {size}}}")
print(f"{{size}} shows the name, {size} the value")
# ✅ Expected output:
# Sets are written like {1, 2, 3}
# {size} shows the name, 3 the valueA single brace on its own is a SyntaxError, and like every SyntaxError it stops the file before any line runs. A brace left open, as in print(f"Hi {name"), gives SyntaxError: f-string: expecting '}', and a lone closing brace, as in print(f"Hi }"), gives SyntaxError: f-string: single '}' is not allowed.
The = form shows what you're printing
An = after the expression prints the expression as well as its value, which is handy while you hunt for a bug:
x = 7
name = "Ada"
print(f"{x=}")
print(f"{x * 2 = }")
print(f"{name=}")
print(f"{x=:.2f}")
# ✅ Expected output:
# x=7
# x * 2 = 14
# name='Ada'
# x=7.00Spaces around the = are kept in the output, and a spec can follow it. name='Ada' has quotes because the = form shows each value the way you'd write it in code, so the text "7" and the number 7 look different. For bigger programs, Logging, Debugging & Error Handling at Scale covers the logging module.
An f-string is made once; .format() fills a template later
An f-string is worked out when its line runs, with the values the names have at that moment. Changing a variable afterwards doesn't change text that's already made. When you need a template that's filled in later, .format() does it: its {} slots are filled by its arguments, in order, and take the same specs after a colon. The oldest style, %, still turns up in older code and in logging calls:
cost = 10
label = f"Price: {cost}"
cost = 12
print(label)
template = "{} owes {:.2f}"
print(template.format("Ada", 7.5))
print(template.format("Ben", 12))
print("%s owes %.2f" % ("Cleo", 3))
# ✅ Expected output:
# Price: 10
# Ada owes 7.50
# Ben owes 12.00
# Cleo owes 3.00In the % style, %s stands for text and %.2f for a number with two decimals. Give .format() fewer values than it has slots, and it stops:
template = "{} owes {:.2f}"
print(template.format("Ada"))
# ✅ Expected error:
# IndexError: Replacement index 1 out of range for positional args tuple% fails in the same situation, with a TypeError. For text you write in the code, an f-string is the usual choice. .format() earns its place when the template exists before the values do, such as a message kept in a settings file.
Practice: a receipt line
Fill the three blanks with the values in the hint lines, in order: the missing f, two decimals for the total, and a whole-number percentage for the tax rate.
item = "Notebook"
cost = 3.5
qty = 4
print(___"{item}: {qty} x {cost:.2f}")
print(f"Total: {cost * qty:___}")
print(f"Tax: {0.2:___}")
# 👉 replace ___ with f
# 👉 replace ___ with .2f
# 👉 replace ___ with .0%
# ✅ Expected output:
# Notebook: 4 x 3.50
# Total: 14.00
# Tax: 20%On your own: a scoreboard
A game keeps its scores in a dictionary: scores = {"Ada": 1520, "Ben": 980, "Cleo": 12750}. Print one line per player: the name on the left of 6 characters, the score on the right of 8 with a comma between the thousands, then the player's share of all the points, on the right of 8, as a percentage with one decimal. Cleo's line should end with 12,750 and 83.6%. Then compare with this solution:
scores = {"Ada": 1520, "Ben": 980, "Cleo": 12750}
everyone = sum(scores.values())
for name, points in scores.items():
print(f"{name:<6}{points:>8,}{points / everyone:>8.1%}")
# ✅ Expected output:
# Ada 1,520 10.0%
# Ben 980 6.4%
# Cleo 12,750 83.6%sum(scores.values()) adds up all the points once, before the loop. Each spec puts the alignment and width first, then the comma or the decimals.
Practice quiz
name = "Ada", then print("Hi {name}"). What prints?
- Hi Ada
- Hi {name}
- An error
- Hi name
Answer: Hi {name}. Without the f before the quote, the braces are ordinary text.
What does f"{19.5:.2f}" give?
- 19.5
- 20
- 19.50
- 19.500
Answer: 19.50. .2f always shows two digits after the point.
What does f"{15:.0%}" give?
- 15%
- 0.15%
- 1500%
- An error
Answer: 1500%. % multiplies by 100 first, so a share should be written as a fraction, 0.15.
average = 10 / 2, then f"{average:d}". What happens?
- It gives 5
- It gives 5.0
- It gives 05
- It stops with ValueError: Unknown format code 'd' for object of type 'float'
Answer: It stops with ValueError: Unknown format code 'd' for object of type 'float'. 10 / 2 is the float 5.0, and d is only for whole numbers. Use .0f, or int() first.
What does f"[{42:5}]" give?
- [ 42]
- [42 ]
- [00042]
- [ 42 ]
Answer: [ 42]. Numbers line up on the right of their width unless you say otherwise.
What does f"[{'Wireless Mouse':<6}]" give?
- [Wirele]
- [Wireless Mouse]
- [Wireless Mouse ]
- An error
Answer: [Wireless Mouse]. A width is a minimum, and a longer value is never cut.
n = 5, then f"{{{n}}}". What does it give?
- {5}
- {{5}}
- {n}
- 5
Answer: {5}. {{ and }} each print one brace, and {n} in the middle is filled in.
cost = 10, label = f"Price: {cost}", cost = 12, then print(label). What prints?
- Price: 12
- Price: {cost}
- An error
- Price: 10
Answer: Price: 10. The f-string was made when its line ran. Changing cost afterwards doesn't change it.
Continue this course
- Previous: Lambda Functions
- Next: String Methods — split, join, strip, replace and the string methods you'll use daily
- Quick reference: Python cheat sheet › Strings
- From the blog: 10 Python Tips Every Beginner Should Know
Frequently asked questions
Which Python version do f-strings need?
Python 3.6 or later, so any Python you install today has them. The = form arrived in Python 3.8, and using the same quotes inside the braces as around the string in Python 3.12.
Can I build an SQL query with an f-string?
Not from values a user typed. An f-string pastes text in exactly as it is, so a value with a quote mark in it can change what the query does, which is called SQL injection. Database libraries take the values separately, as parameters; Using SQLite & ORMs (SQLAlchemy) in Python shows how. The same goes for shell commands.
Can an f-string run over several lines?
Yes. Triple quotes make a string that runs over several lines, and an f before them works the same way. Two strings written side by side inside brackets are also joined into one, and each can be an f-string, which keeps a long line readable.