livepython.net
CHAPTER 12Working With Strings
12.4  FORMATTING

Python f-string Formatting: Width, Align, Commas

Give a Value a Width in an f-string

In an f-string, a colon and a number after the value set its width: the smallest number of characters it takes up. Python fills the rest with spaces. {name:10} means "give name 10 characters of room".

Think of it like the boxes on a paper form: every box is the same size, whether you write a short name or a long one in it.

PYTHONedit me
name = "Sunny"
score = 42
print(f"[{name:10}]")
print(f"[{score:6}]")
OUTPUT
[Sunny     ]
[    42]

The square brackets are only there so you can see the spaces.

The rules

  • {value:10} makes the value at least 10 characters wide.
  • By default, text sits on the left and numbers sit on the right.
  • A value that is too long is never cut. It simply sticks out.
  • The colon is the same one you used for :.2f in chapter 5. Everything after it says how to show the value.
PYTHONedit me
name = "Rocky"
print(f"[{name:3}]")
OUTPUT
[Rocky]

Why widths are useful: columns

Give every row the same widths, and the columns line up by themselves:

PYTHONedit me
items = ["Tea", "Sandwich", "Cake"]
prices = [20, 150, 80]
for i in range(len(items)):
    print(f"{items[i]:10}{prices[i]:5}")
OUTPUT
Tea          20
Sandwich    150
Cake         80

Without widths, the prices would start at a different place on every line.

Common beginner doubt: "Is the width the number of spaces added?" No, it's the total size of the box. "Sunny" has 5 characters, so {name:10} adds 5 spaces to fill 10.

{value:10} gives a value 10 characters of room: text sits left, numbers sit right.

your turnPredict the output

What will this print?

x = 7 print(f"[{x:3}]")
Your turn! What will this code show on the screen?
your turnType the output

Type what this prints

word = "Hi" print(f"{word:5}|")
Read the code line by line, then type the output exactly.

Align Text Left, Right or Centre

Put an alignment sign right before the width to choose where the value sits in its box: < for left, > for right and ^ for centre.

Think of it like the three align buttons in a word processor: the text is the same, only its place on the line changes.

PYTHONedit me
name = "Lucky"
print(f"[{name:<9}]")
print(f"[{name:>9}]")
print(f"[{name:^9}]")
OUTPUT
[Lucky    ]
[    Lucky]
[  Lucky  ]

The rules

You writeThe value sits
{x:<10}on the left of 10 characters
{x:>10}on the right
{x:^10}in the centre
{x:*^10}in the centre, with * instead of spaces
  • The sign comes after the colon and before the width.
  • A character before the sign is the fill: it's used instead of spaces.
  • When the centre can't be exact, the extra space goes on the right.

Fill characters make banners

PYTHONedit me
title = "Menu"
print(f"{title:*^14}")
print(f"{title:-<14}")
print(f"{title:.>14}")
OUTPUT
*****Menu*****
Menu----------
..........Menu

Avoid: forgetting the colon

PYTHONedit me
name = "Lucky"
print(f"[{name>9}]")
OUTPUT
TypeError: '>' not supported between instances of 'str' and 'int'

Without the colon, Python reads name>9 as a comparison: "is name greater than 9?" And text can't be compared with a number. The colon is what starts the formatting part.

Common beginner doubt: "When should I use which?" Left for words, right for numbers (so the digits line up), and centre for titles and headings.

Write < for left, > for right and ^ for centre, right before the width.

your turnFill the gap

Push the word to the right

item = "Tea" print(f"[{item:?}]")

It should print: [ Tea]

Which piece makes this code work?
your turnPredict the output

What will this print?

print(f"[{'ab':^6}]")
Your turn! What will this code show on the screen?

Format Numbers: Decimals, Commas and Percent

After the colon, you can also tell Python how to write a number: how many decimals, whether to add thousands commas, or to show it as a percent. You already know :.2f from chapter 5. Now you can add more.

Think of it like a bank statement: every amount has commas and exactly two decimals, so you can read big numbers at a glance.

PYTHONedit me
price = 1234567.891
print(f"{price:.2f}")
print(f"{price:,}")
print(f"{price:,.2f}")
population = 1400000000
print(f"{population:,}")
OUTPUT
1234567.89
1,234,567.891
1,234,567.89
1,400,000,000

The rules

You writeFor 1234.5 you get
{x:.2f}1234.50
{x:,}1,234.5
{x:,.2f}1,234.50
{x:>10,.2f} 1,234.50
{x:.1%}123450.0% (the value times 100, then a % sign)

The order is always: alignment, width, comma, then the decimals. Read {x:>10,.2f} as "on the right, 10 wide, with commas, 2 decimals".

Percent

% multiplies by 100 for you, so store the share as a decimal:

PYTHONedit me
score = 0.875
print(f"{score:.1%}")
print(f"{score:.0%}")
OUTPUT
87.5%
88%

A column of amounts

Width plus commas plus decimals lines up the decimal points:

PYTHONedit me
amounts = [5, 250.5, 12000]
for a in amounts:
    print(f"Rs.{a:>10,.2f}")
OUTPUT
Rs.      5.00
Rs.    250.50
Rs. 12,000.00

Avoid: number formats on text

PYTHONedit me
price = input()
print(f"{price:,.2f}")
OUTPUT
ValueError: Unknown format code 'f' for object of type 'str'

input() gives the text "1500", and the f format (a float with decimals) only works on numbers. Convert first with float(input()).

Common beginner doubt: "Does :.2f change the number?" No. It only changes how it's shown. The variable still holds every decimal.

, adds thousands commas, .2f fixes two decimals, and a width lines them up: {x:>10,.2f}.

your turnType the output

Type what this prints

print(f"{2500000:,}")
Read the code line by line, then type the output exactly.
your turnFix the code

Make it print: Total: 1,250.50 when the user types 1250.5

It should print: Total: 1,250.50

The user types: 1250.5

total = input()
print(f"Total: {total:,.2f}")
This code does not work yet. Fix it, then press Run.

Practice: Formatting

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 107.Python Program to Format a Number with CommasEasySolve
  2. 108.Python Program to Print a Multiplication Table in ColumnsMediumSolve
  3. 109.Python Program to Print a Neat Bill from Input LinesHardSolve