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.
name = "Sunny"
score = 42
print(f"[{name:10}]")
print(f"[{score:6}]")[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
:.2fin chapter 5. Everything after it says how to show the value.
name = "Rocky"
print(f"[{name:3}]")[Rocky]
Why widths are useful: columns
Give every row the same widths, and the columns line up by themselves:
items = ["Tea", "Sandwich", "Cake"]
prices = [20, 150, 80]
for i in range(len(items)):
print(f"{items[i]:10}{prices[i]:5}")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.