Beginner   Chapter 34 · 25 min read · Module 3: Python Strings

String Formatting

Learning objectives
  • After this chapter you can fill placeholders with str.format() using automatic, numbered and named fields.
  • You can control decimals, width, alignment and padding with a format specification.
  • You can read and write simple percent-style formats such as %s, %d and %.2f.
  • You can print a neat table with aligned columns.
  • You can escape literal braces and percent signs.

String formatting means putting values into a piece of text in a controlled way. Instead of joining many small strings with plus signs and converting every number by hand, you write a template with holes in it and let Python fill the holes. You can also control how a value looks: how many decimals, how wide the column is, and whether it is aligned left or right.

Python has three main styles. The oldest is the percent operator, the middle one is the format() method, and the newest is the f-string, which has its own chapter. In this chapter you will focus on the percent style and the format() method, plus the format specification mini-language that all styles share.

Learning these tools helps you print tidy tables, money amounts, percentages and padded numbers. You will also be able to read older code, which still uses the percent operator and format() a lot.

Why format strings?

Look at the line "Total: " + str(price) + " for " + str(qty) + " items". It works, but it is long and hard to read. A format template shows the final shape of the sentence in one piece, with markers where values go. It is also easier to change, and it lets you set the number of decimal places, which plain joining cannot do.

Placeholder: a marker inside a template string, such as {} or %s, that is replaced by a value when the string is formatted

The format() method

Write curly braces {} where values should go, then call .format() with the values. By default the braces are filled in order. You can use numbers like {0} and {1} to choose a value by position, which lets you use one value more than once. You can also use names like {name} and pass keyword arguments.

Example 1: Automatic, numbered and named fields
print("{} is {} years old".format("Asha", 21))
print("{1} before {0}".format("b", "a"))
print("{0} and {0} again".format("echo"))
print("{name} lives in {city}".format(name="Ravi", city="Goa"))
Asha is 21 years old a before b echo and echo again Ravi lives in Goa

Format specifications

Inside the braces you can add a colon and a format specification. The general shape is {value:fill align width , .precision type}. The most useful parts are the width (how many characters the field takes), the alignment (< left, > right, ^ centre), the precision (digits after the decimal point), and the type (d integer, f fixed decimals, % percent, e scientific, s string).

SpecificationMeaningExample valueResult
:.2ftwo decimals3.141593.14
:5dwidth 5, numbers right-aligned42 42
:<6left-align in width 6"ab"ab
:*^7centre with * as fill"hi"hi*
:,thousands separator12345671,234,567
:.1%percent with 1 decimal0.25625.6%
:05dzero-padded width 54200042
Example 2: Numbers
pi = 3.14159265
print("{:.2f}".format(pi))
print("{:8.3f}|".format(pi))
print("{:05d}".format(42))
print("{:,}".format(1234567))
print("{:.1%}".format(0.256))
print("{:b} {:x} {:o}".format(10, 255, 8))
3.14 3.142| 00042 1,234,567 25.6% 1010 ff 10
Example 3: Alignment and fill
print("[{:<8}]".format("left"))
print("[{:>8}]".format("right"))
print("[{:^8}]".format("mid"))
print("[{:*^9}]".format("hi"))
print("[{:>6.1f}]".format(2.55))
[left ] [ right] [ mid ] [***hi****] [ 2.5]

The percent operator

The older style uses % between a template and the values. Placeholders include %s for strings, %d for integers and %f for floats. With more than one value, put them in a tuple. You can write a precision such as %.2f. This style is still common in old code and in the logging module, but new code usually prefers format() or f-strings.

Example 4: Percent formatting
print("%s scored %d" % ("Asha", 90))
print("%.2f" % 2.5)
print("%5d|" % 42)
print("%-5d|" % 42)
print("%05.1f" % 3.14159)
print("100%% done")
print("100%% done" % ())
Asha scored 90 2.50 42| 42 | 003.1 100%% done 100% done
To print a real percent sign in a % template, write %%. In format() a real brace is written by doubling it: {{ and }}.

Making tables

Width and alignment make neat columns. A common plan is to left-align text and right-align numbers. Use a fixed width bigger than the longest value in the column. You can even take the width from a variable by nesting braces, such as {:>{width}}.

Example 5: A small table
items = [("Pen", 3, 1.5), ("Notebook", 12, 24.25)]
print("{:<10}{:>5}{:>9}".format("Item", "Qty", "Price"))
for name, qty, price in items:
    print("{:<10}{:>5}{:>9.2f}".format(name, qty, price))
width = 6
print("{:>{w}}".format("ok", w=width))
print("{{literal}} {}".format(1))
Item Qty Price Pen 3 1.50 Notebook 12 24.25 ok {literal} 1
Example 6: Format user input
name = input()
marks = float(input())
print("{} scored {:.1f}%".format(name, marks))
Meera scored 87.5%

Rounding notes

Formatting rounds the displayed number but does not change the value itself. Floats are stored in binary, so a value like 2.675 may be slightly below the true decimal, and {:.2f} can give 2.67 instead of 2.68. This is normal. For money in serious programs, the decimal module is the right tool.

There is also the built-in format(value, spec) function, which applies the same specification to one value: format(3.14159, ".2f") gives 3.14. The str.format_map and string.Template tools exist too, but you will use them rarely. Mastering the specification mini-language pays off in every style, because f-strings use exactly the same rules after the colon.

Python syntax

Syntax
"{} and {}".format(a, b)
Syntax
"{:.2f}".format(number)
Syntax
"{:>10}".format(text)
Syntax
"%s has %d items" % (name, count)
Syntax
format(value, ".2f")

Real-world applications

  • Printing prices with exactly two decimals.
  • Making aligned columns in console reports and receipts.
  • Showing percentages and numbers with thousands separators.
  • Building log messages and zero-padded IDs such as 00042.

Common mistakes

Mistake: Giving format() fewer values than placeholders.
Fix: Count the {} fields and pass one value for each, or an IndexError is raised.
Mistake: Using % with several values without a tuple.
Fix: Write '%s %d' % (name, count) with the values inside parentheses.
Mistake: Passing a string to the f type, as in '{:.2f}'.format('3.5').
Fix: Convert it first with float(). The f type needs a number.
Mistake: Forgetting to double braces or percent signs for literal characters.
Fix: Use {{ and }} in format(), and %% in percent templates.

Important tips

  • Use named fields when a template has many values.
  • Use width and alignment to make clean tables.
  • Remember that formatting changes only how a value is shown, not the value.

Key points summary

  • {} placeholders are filled by format() in order, by number or by name.
  • A specification after the colon sets align, width, precision and type.
  • .2f shows two decimals; , adds thousands separators.
  • The % operator uses %s, %d and %f, with a tuple for many values.
  • Use {{ }} and %% for literal characters.

Exam and interview points

  • '{:>8}'.format('x') right-aligns in 8 characters.
  • '{:.3f}' gives three digits after the point.
  • '%d' % 3.9 gives '3' because it truncates.
  • format() fields can be automatic, numbered or named, but mixing automatic and numbered is an error.

Quick revision

  • Template.format(values).
  • {:<w} left, {:>w} right, {:^w} centre.
  • {:.nf} for n decimals.
  • %s %d %f with a tuple.

Frequently asked questions

Which formatting style should I use?

For new code, f-strings are the most readable and are covered in the next chapter. Knowing format() and % helps you read older code.

How do I show exactly two decimal places?

Use the specification .2f, for example '{:.2f}'.format(x) or '%.2f' % x.

Why does format give 2.67 for 2.675?

The float 2.675 is stored as a binary number that is a little smaller than 2.675, so it rounds down. Use the decimal module when exact decimal rounding matters.

How do I print a curly brace?

Double it: '{{' prints { and '}}' prints }.

Practise this chapter

19 practice questions Take the chapter quiz

Related chapters