Skip to content

Module 7 · Strings — topic 19 of 22

String formatting

Format values into text with str.format() and format specifiers: width, alignment, decimal places, thousands separators, percentages and padding, plus the older % style you may meet in existing code.

Beginner 12 min read·Lesson 100 of 306 in Python Programming

Learning objectives

  • Use str.format() with positional and named fields
  • Apply format specifiers for numbers and alignment
  • Recognise %-style formatting in older code

Definition

Format values into text with str.format() and format specifiers: width, alignment, decimal places, thousands separators, percentages and padding, plus the older % style you may meet in existing code.

Introduction

Formatting means inserting values into text in a controlled way: with a fixed number of decimals, aligned in columns, padded with zeros. Python has three styles; this lesson covers str.format() and the format specifier mini-language, and the next covers f-strings, which use the same specifiers.

Why it matters

Reports, receipts, tables and log messages must look tidy and be easy to read. Format specifiers turn 1234567.891 into 12,34,567.89-style readable figures, align names in columns and show percentages without manual arithmetic.

Detailed explanation

"{} scored {}".format(name, marks) fills each {} with the next argument. Numbers inside braces pick arguments by position, {0}, and names pick keyword arguments, {name}.

A format specifier follows a colon inside the braces: {value:spec}.

SpecifierMeaningExampleResult
.2f2 decimal places{:.2f}3.14
,thousands separator{:,}1,234,567
>10right-align in 10{:>10}' right'
<10left-align in 10{:<10}'left '
^10centre in 10{:^10}' centre '
05dzero-pad to 5 digits{:05d}00042
.1%percentage{:.1%}75.0%
+always show sign{:+}+5

Specifiers combine in a fixed order: fill and alignment, sign, width, comma, precision, type. {:>12,.2f} means right-aligned in 12 characters, with commas and 2 decimals.

The built-in format(value, spec) applies a specifier directly: format(0.756, ".1%").

Older code uses % formatting: "%s scored %d" % (name, marks). It still works, but str.format() and f-strings are clearer.

Note that the , separator groups in thousands (1,234,567), the international style, not the Indian lakh style.

Syntax

Python
"{} has {:.2f}".format(name, amount)
"{name:<10}|{score:>5}".format(name=n, score=s)
format(value, ",.2f")
  • {} are replacement fields.
  • A colon starts the format specifier.
  • Named fields make long templates readable.

Code examples

Positional and named fields

Python
print("{} scored {}".format("Asha", 82))
print("{1} before {0}".format("A", "B"))
print("{name} is {age}".format(name="Ravi", age=21))
Output
Asha scored 82
B before A
Ravi is 21

Number formats

Python
print("{:.2f}".format(3.14159))
print("{:,}".format(1234567))
print("{:05d}".format(42))
print("{:.1%}".format(0.756))
print("{:+}".format(5))
Output
3.14
1,234,567
00042
75.6%
+5

More examples

An aligned receipt

Python
items = [("Notebook", 3, 45.0), ("Pen", 10, 12.5), ("Geometry box", 1, 189.0)]
print("{:<14}{:>4}{:>10}".format("Item", "Qty", "Amount"))
print("-" * 28)
total = 0
for name, qty, price in items:
amount = qty * price
total += amount
print("{:<14}{:>4}{:>10.2f}".format(name, qty, amount))
print("-" * 28)
print("{:<18}{:>10,.2f}".format("Total", total))
print("Invoice no. {:06d}".format(127))
Output
Item           Qty    Amount
----------------------------
Notebook         3    135.00
Pen             10    125.00
Geometry box     1    189.00
----------------------------
Total                 449.00
Invoice no. 000127

Step-by-step explanation

  • {:<14} left-aligns the item name in 14 characters; {:>4} and {:>10} right-align numbers.
  • {:>10.2f} shows each amount with two decimals, right-aligned so the decimal points line up.
  • The total line uses {:>10,.2f}, adding a thousands separator if the total grows.
  • {:06d} zero-pads the invoice number to six digits.

Expected output

Running “An aligned receipt” prints exactly:

TextOutput
Item Qty Amount
----------------------------
Notebook 3 135.00
Pen 10 125.00
Geometry box 1 189.00
----------------------------
Total 449.00
Invoice no. 000127

Practical applications

  • Billing systems format receipts with aligned columns and fixed decimals.
  • Dashboards show percentages with one decimal place.
  • Order IDs and roll numbers are zero-padded for consistent length.

Best practices

  • Format only for display; keep values numeric for calculations.
  • Use named fields in long templates.
  • Prefer f-strings in new code; the specifiers are identical.

Common mistakes

Formatting a string with a number specifier

Avoid

"{:.2f}".format("3.5")

Prefer

"{:.2f}".format(float("3.5"))

f-style number specifiers need a number, not text; convert first.

Rounding with format and then calculating

Avoid

total = "{:.2f}".format(x) + 1

Prefer

total = round(x, 2) + 1

Formatting produces a string for display; keep numbers as numbers for maths.

Key takeaways

  • str.format() fills {} fields with arguments.
  • Specifiers after a colon control decimals, width, alignment and separators.
  • %-formatting is legacy; use format() or f-strings.

Try it yourself

  1. 1
    Print a table of three products with names left-aligned and prices right-aligned to 2 decimals.
  2. 2
    Format 0.4567 as a percentage with two decimal places.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic