Module 2 · Beginner · Python basics

Python f-strings: format output the easy way

Python f-strings explained with examples: insert variables, round decimals, add commas, percentages, padding and alignment, dates, and the = debug trick.

By theprogrammers team · · 4 min read

Sooner or later, every program needs to show results neatly: a price with two decimal places, a big number with commas, a receipt where the columns line up. f-strings are Python's easiest and fastest way to do all of this.

This guide covers putting variables and expressions into text, formatting numbers, aligning columns, dates, a handy debugging trick and the mistakes to avoid.

The basics

Put an f before the opening quote, and put any variable inside curly braces:

name = "Ahana"
city = "Kanpur"
print(f"{name} lives in {city}.")    # Ahana lives in Kanpur.

Without f-strings, you'd have to glue pieces together and convert numbers yourself:

age = 20
print(name + " is " + str(age) + " years old.")    # works, but clumsy
print(f"{name} is {age} years old.")               # much clearer

Expressions inside the braces

The braces can hold any Python expression, not just variable names:

price = 250
qty = 3
print(f"Total: {price * qty}")             # Total: 750
print(f"Name in capitals: {name.upper()}") # Name in capitals: AHANA
print(f"Adult: {age >= 18}")               # Adult: True

Keep them short, though. If the expression gets complicated, calculate it on its own line first and give it a name.

Formatting numbers

Add a colon after the value, then a format specifier that says how to show it.

SpecifierMeaningExampleResult
.2f2 decimal placesf"{3.14159:.2f}"3.14
.0fNo decimals, roundedf"{7.6:.0f}"8
,Thousands separatorf"{1500000:,}"1,500,000
,.2fBothf"{1234.5:,.2f}"1,234.50
.1%Percentage, 1 decimalf"{0.256:.1%}"25.6%
03dPad with zeros to 3 digitsf"{7:03d}"007
b, xBinary, hexadecimalf"{255:b}"11111111
marks = 437
total = 500
print(f"You scored {marks / total:.1%}")    # You scored 87.4%

The , separator groups digits in threes (1,500,000), the international style. Indian-style grouping such as 15,00,000 isn't built in.

Lining things up: width and alignment

A number after the colon sets a minimum width. Then < aligns left, > right and ^ centres:

name = "Ahana"
print(f"[{name:<10}]")    # [Ahana     ]
print(f"[{name:>10}]")    # [     Ahana]
print(f"[{name:^11}]")    # [   Ahana   ]
print(f"[{name:*<8}]")    # [Ahana***]: a fill character before the arrow

Text aligns left by default and numbers align right. Combine width with number formats to print tidy tables:

items = [("Notebook", 3, 45.0), ("Pen", 10, 12.5), ("Geometry box", 1, 180.0)]

print(f"{'Item':<14}{'Qty':>5}{'Amount':>10}")
for item, qty, price in items:
    print(f"{item:<14}{qty:>5}{qty * price:>10.2f}")
Item            Qty    Amount
Notebook          3    135.00
Pen              10    125.00
Geometry box      1    180.00

Formatting dates

Dates accept the same codes as strftime:

from datetime import date

today = date(2026, 12, 2)
print(f"{today:%d %b %Y}")      # 02 Dec 2026
print(f"{today:%A}")            # Wednesday
print(f"{today:%d/%m/%Y}")      # 02/12/2026

%d is the day, %m the month number, %b the short month name, %Y the four-digit year and %A the weekday.

The = trick for debugging

Add = after an expression and Python prints the expression and its value. It's the quickest way to check what your variables hold:

x = 3
total = 750
print(f"{x=}, {total=}")    # x=3, total=750

Quotes, braces and multiple lines

  • Quotes: if the f-string uses double quotes, use single quotes inside the braces: f"{data['name']}". Newer Python versions allow the same quotes, but different ones work everywhere.
  • Literal braces: double them to show a real brace. f"{{x}}" prints {x}.
  • Several lines: use triple quotes, f"""...""".

Older ways you'll see in other code

"Hello, {}!".format(name)    # str.format()
"Hello, %s!" % name          # % formatting, the oldest style

Both still work, and you'll meet them in older tutorials and libraries. For new code, use f-strings: they're shorter, easier to read and faster.

Key takeaways

  • Put f before the quotes and values inside { }.
  • After a colon, .2f sets decimals, , adds separators and % shows percentages.
  • Width and <, >, ^ line up columns.
  • {x=} prints a variable's name and value, which is great for debugging.

Practice

  1. Print Pi is roughly 3.142 using math.pi.
Show the answer
import math
print(f"Pi is roughly {math.pi:.3f}")
  1. Given salary = 1250000, print Annual salary: ₹1,250,000.00.
Show the answer
salary = 1250000
print(f"Annual salary: ₹{salary:,.2f}")
  1. A student got 42 out of 50. Print Score: 84.0%.
Show the answer
print(f"Score: {42 / 50:.1%}")
  1. Print a multiplication table for 7, with the results lined up on the right:
 7 x  1 =   7
 7 x  2 =  14
...
 7 x 10 =  70
Show the answer
n = 7
for i in range(1, 11):
    print(f"{n:>2} x {i:>2} = {n * i:>3}")
  1. Print invoice numbers INV-001 to INV-005.
Show the answer
for i in range(1, 6):
    print(f"INV-{i:03d}")

Interview questions

What is an f-string?

A formatted string literal, added in Python 3.6. Prefixing a string with f lets you embed expressions in curly braces; Python evaluates them at runtime and inserts the results, optionally formatted with a specifier after a colon.

What are the ways to format strings in Python?

f-strings (f"{x}"), str.format() ("{}".format(x)), printf-style % formatting ("%s" % x), and string.Template. f-strings are the most readable and usually the fastest.

How do you print a literal curly brace in an f-string?

Double it: f"{{" prints { and f"}}" prints }. So f"{{value}}" prints {value}.

What does f"{x=}" do?

Added in Python 3.8, it prints the expression text, an equals sign and the value, such as x=3. It's used for quick debugging.

What to learn next

  1. Read numbers and text from the user safely with Python input and type conversion.
  2. Learn more string skills in Python strings and string methods.