Python String Formatting
What you will learn
- The shape of a format spec:
[fill][align][sign][#][0][width][,][.precision][type] - Alignment and width for text and numbers
- Signs, zero padding and grouping
- Types:
d,b,x,e,f,g,% - Nested specs, formatting dates, and
format() - The older
.format()method and%operator
This lesson builds on lesson 4.5. The same format codes work in f-strings, in format(value, spec) and in "...".format(...).
1. The shape of a format spec
After the colon in {value:spec} you can write a spec made of these parts, in this order, all optional:
fill + align + sign + # + 0 + width + grouping + .precision + type
| Part | Examples | Meaning |
|---|---|---|
| fill | *, -, 0 |
the padding character (default: space) |
| align | <, >, ^, = |
left, right, centre, or padding after the sign |
| sign | +, -, space |
how to show the sign of numbers |
# |
#x |
show the prefix: 0b, 0o, 0x |
0 |
06 |
pad numbers with zeros |
| width | 10 |
minimum number of characters |
| grouping | , or _ |
thousands separator |
| precision | .2 |
digits after the point (numbers) or maximum length (text) |
| type | d, f, x, % ... |
how to show the value |
You rarely use all the parts at once. We take them one at a time.
Quick check: in `{price:>10.2f}`, what is the width, and what is the type?
Width 10 and type f (a decimal number). The > aligns right and .2 gives two decimals.
2. Width and alignment
name = "Rina"
print(f"{name:>8}|")
print(f"{name:<8}|")
print(f"{name:^8}|")
print(f"{name:*^9}")
print(f"{name:->8}")
Rina|
Rina |
Rina |
**Rina***
----Rina
| Align | Meaning | Default for |
|---|---|---|
< |
left | text |
> |
right | numbers |
^ |
centre | |
= |
padding goes between the sign and the digits |
A fill character comes just before the align symbol: *^9 means "centre in width 9 with *". A width smaller than the text changes nothing, because text is never cut by a width.
print(f"{12:>6}|{12:<6}|{12:^6}|")
print(f"{'x':5}|{5:5}|")
12|12 | 12 |
x | 5|
Notice the defaults: with no align, text goes left and numbers go right.
3. Signs and zero padding
x = 7
print(f"{x:+d}", f"{-x:+d}", f"{x: d}")
print(f"{12:06}|{-12:06}|{12:=6}|{-12:=6}|")
+7 -7 7
000012|-00012| 12|- 12|
| Sign | Meaning |
|---|---|
+ |
always show the sign |
- |
only show it for negatives (default) |
| space | a space before positive numbers, - before negatives |
06 pads with zeros and keeps the minus sign at the front. With = and a width, the padding goes between the sign and the digits.
4. Grouping thousands
print(f"{1234567:,}")
print(f"{1234567:_}")
print(f"{1234567.891:,.2f}")
1,234,567
1_234_567
1,234,567.89
, and _ insert separators every three digits. (For binary, octal and hex, _ groups every four digits.)
5. Precision
For numbers, precision is the number of digits after the point (with f). For text, it is the maximum length:
price = 1234.5678
print(f"{price:.2f}|{price:10.1f}|{price:<12.2f}|")
print(f"{'abcdef':.3}")
1234.57| 1234.6|1234.57 |
abc
Rounding follows the stored value and "ties to even" rules (lessons 3.3 and 3.4):
print(f"{2.5:.0f}", f"{3.5:.0f}", f"{2.675:.2f}")
2 4 2.67
6. Types
The type letter at the end says how to show the value:
| Type | For | Meaning | Example (255 or 1234.5) |
|---|---|---|---|
d |
integers | decimal digits | f"{255:d}" → 255 |
b |
integers | binary | f"{255:b}" → 11111111 |
o |
integers | octal | 377 |
x / X |
integers | hexadecimal | ff / FF |
c |
integers | the character with that code | f"{65:c}" → A |
f |
floats | fixed point | f"{1234.5:.1f}" → 1234.5 |
e |
floats | scientific | f"{1234.5:e}" → 1.234500e+03 |
g |
floats | general (shortest sensible) | f"{12345.6789:.3g}" → 1.23e+04 |
% |
floats | percentage (multiplies by 100) | f"{0.256:.1%}" → 25.6% |
s |
text | text (the default) |
print(f"{255:b}", f"{255:#b}", f"{255:o}", f"{255:x}", f"{255:#X}", f"{255:08b}", f"{65:c}")
print(f"{0.256:.1%}", f"{1234.5:e}", f"{1/3:.3g}", f"{12345.6789:.3g}")
11111111 0b11111111 377 ff 0XFF 11111111 A
25.6% 1.234500e+03 0.333 1.23e+04
Using the wrong type for the value is an error: f"{'text':d}" raises ValueError: Unknown format code 'd' for object of type 'str'.
7. Nested fields: width from a variable
You can use { } inside the spec to choose the width or precision with variables:
w, p = 10, 3
print(f"{3.14159265:{w}.{p}f}|")
print(f"{name:>{w}}|")
3.142|
Rina|
8. Dates and times
Dates (lesson 17.1 covers them) use their own codes after the colon:
import datetime
dt = datetime.datetime(2026, 10, 20, 14, 5, 9)
print(f"{dt:%Y-%m-%d}", f"{dt:%H:%M}", f"{dt:%d %B %Y}", f"{dt:%A}")
2026-10-20 14:05 20 October 2026 Tuesday
9. The format() function and .format()
The built-in format(value, spec) applies a spec to one value:
print(format(1234.5, ",.1f"), format("hi", ">5"), format(255, "x"), format(0.5, "%"))
1,234.5 hi ff 50.000000%
Before f-strings, text was built with the .format() method. You will see it in older code. The braces take positions or names:
name = "Rina"
age = 25
print("{} is {}".format(name, age))
print("{1} {0}".format("a", "b"))
print("{n} is {a}".format(n=name, a=age))
print("{:>6.2f}".format(1234.5678))
print("{0:,}".format(1234567))
Rina is 25
b a
Rina is 25
1234.57
1,234,567
10. The old % operator
The oldest style uses % with codes such as %s (text), %d (whole number), %f (decimal) and %x (hex). You will meet it in old code and in logging (lesson 17.9):
print("%s is %d years, %.2f" % (name, age, 1234.5678))
print("%5s|%-5s|%05d" % ("a", "b", 42))
print("%d%% done" % 50)
Rina is 25 years, 1234.57
a|b |00042
50% done
To show a real percent sign inside a % template, write %%.
For new code, use f-strings: they are shorter and the values sit next to the text. .format() is useful when the template is stored apart from the values.
Worked example: a neat table
Print three items in aligned columns: name left-aligned in 10, quantity right-aligned in 3, price right-aligned in 8 with two decimals.
rows = [("Rice", 2, 55.5), ("Lentils", 10, 120), ("Oil", 1, 1234.567)]
print(f"{'Item':<10}{'Qty':>3}{'Price':>10}")
print("-" * 23)
for item, qty, price in rows:
print(f"{item:<10}{qty:>3}{price:>10,.2f}")
Item Qty Price
-----------------------
Rice 2 55.50
Lentils 10 120.00
Oil 1 1,234.57
| Spec | Meaning |
|---|---|
{item:<10} |
text, left-aligned in width 10 |
{qty:>3} |
whole number, right-aligned in width 3 |
{price:>10,.2f} |
decimal with commas and 2 places, right-aligned in width 10 |
(The for loop is covered in chapter 6.) The items and prices are made up.
Common mistakes
- Using the wrong type letter.
dis for whole numbers,ffor decimals,sfor text. - Forgetting that width is a minimum. Long text is never cut by a width; use precision to cut text.
- Putting the spec parts in the wrong order. The fill must come before the align, and the width before
.precision. - Using
%and.format()in new code when an f-string is clearer. - Expecting
:.0fto round halves up.f"{2.5:.0f}"is2(ties to even).
Key takeaways
- A spec is
[fill][align][sign][#][0][width][,][.precision][type]; everything is optional. <,>,^align; text defaults left, numbers right.+,0,,and_handle signs, zero padding and thousands separators.- Types:
d,b,o,x,cfor integers;f,e,g,%for floats. format(value, spec),"...".format(...)and%do the same job as f-strings; prefer f-strings in new code.
Practice
1. Show 3.14159 rounded to 2 decimals, right-aligned in a width of 8.
Show answer
f"{3.14159:>8.2f}" gives 3.14.
2. Show 7 as 007 using a format spec.
Show answer
f"{7:03d}" (or f"{7:03}").
3. What does f"{0.075:.1%}" give?
Show answer
7.5%. The % type multiplies by 100 and adds the sign.
4. Write the spec that shows 1500000 as 1,500,000.
Show answer
f"{1500000:,}".
5. Show the text "menu" centred in width 10 with dashes around it.
Show answer
f"{'menu':-^10}" gives ---menu---.
6. Rewrite "%s scored %d" % (name, score) as an f-string.
Show answer
f"{name} scored {score}".