Beginner Chapter 34 · 25 min read · Module 3: Python Strings
String Formatting
- 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.
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.
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"))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).
| Specification | Meaning | Example value | Result |
|---|---|---|---|
| :.2f | two decimals | 3.14159 | 3.14 |
| :5d | width 5, numbers right-aligned | 42 | 42 |
| :<6 | left-align in width 6 | "ab" | ab |
| :*^7 | centre with * as fill | "hi" | hi* |
| :, | thousands separator | 1234567 | 1,234,567 |
| :.1% | percent with 1 decimal | 0.256 | 25.6% |
| :05d | zero-padded width 5 | 42 | 00042 |
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))print("[{:<8}]".format("left"))
print("[{:>8}]".format("right"))
print("[{:^8}]".format("mid"))
print("[{:*^9}]".format("hi"))
print("[{:>6.1f}]".format(2.55))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.
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" % ())% 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}}.
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))name = input()
marks = float(input())
print("{} scored {:.1f}%".format(name, marks))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
"{} and {}".format(a, b)"{:.2f}".format(number)"{:>10}".format(text)"%s has %d items" % (name, count)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
Fix: Count the {} fields and pass one value for each, or an IndexError is raised.
Fix: Write '%s %d' % (name, count) with the values inside parentheses.
Fix: Convert it first with float(). The f type needs a number.
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