Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python String Formatting (f-strings)

Programs constantly build text out of values: "Total: 450", "Hello, Asha!", a neat table of results. Joining pieces with + and str() works, but it is clumsy. Python's f-strings make it easy: put an f before the opening quote, and write any variable or expression inside curly braces {}.

f-strings

name = "Asha"
age = 21
print(f"Hello, {name}!")
print(f"Next year {name} will be {age + 1}.")
print(f"{name} has {len(name)} letters.")
Output
Hello, Asha!
Next year Asha will be 22.
Asha has 4 letters.

Anything that produces a value can go inside the braces: a variable, a calculation, a function call. Python works it out and puts the result into the text.

Format specifications

After the value, a colon starts a format specification that controls how it looks. The most useful ones:

price = 1234.5678
print(f"{price:.2f}")       # 2 decimals
print(f"{price:,.2f}")      # thousands separator
print(f"{0.256:.1%}")       # as a percentage
print(f"{42:5}|")           # width 5 (numbers go right)
print(f"{'ok':5}|")         # width 5 (text goes left)
print(f"{'ok':>5}|{'ok':^6}|")
print(f"{7:03}")            # pad with zeros
Output
1234.57
1,234.57
25.6%
   42|
ok   |
   ok|  ok  |
007

.2f means "a float with 2 decimals"; the value is rounded, not cut off. A number before the dot is a minimum width, and <, > and ^ align left, right and centre inside it.

Tables with aligned columns

Widths make tidy tables without any extra work:

items = [("Rice", 2, 54.5), ("Milk", 3, 28.0), ("Apples", 1, 120.25)]
for name, qty, price in items:
    print(f"{name:<8}{qty:>3} x {price:>7.2f} = {qty * price:>7.2f}")
Output
Rice      2 x   54.50 =  109.00
Milk      3 x   28.00 =   84.00
Apples    1 x  120.25 =  120.25

Showing the expression too

Writing = after an expression prints the expression and its value, which is very handy while testing: f"{age=}" gives age=21. You may also meet the older ways of formatting, "{} is {}".format(name, age) and "%s is %d" % (name, age). They still work, but f-strings are shorter and easier to read.

Practice exercises

  1. Print "The price of 3 pens is Rs 36.00" with an f-string, using variables for the number, the item and the unit price.
  2. Print the number 9876543.21 with a thousands separator and no decimals.
  3. Print a multiplication table for 9 with the products right-aligned in a width of 3.
  4. Print 0.0725 as a percentage with 2 decimals.