Skip to main content

Section 11.3 Format Spacing

The [fill], [align] and [width] values allow us to control the spacing of elements. This is especially useful for making well aligned columns of data when the values on different lines have different widths.
{:[[fill]align][sign]["#"][0][width][precision][type]}
[width] is the starting point for doing this kind of formatting. It specifies a minimum size for the item. If the item being formatted is shorter than that, spaces are added. (Nothing is done to items that are larger than that value). Here are some examples with _ printed before and after each item to show where spaces were added.
Listing 11.3.1.
Note that spaces were used when we needed padding to fill in space. Those spaces were added before the item (the item is right justified). To change from this default, we can use the [fill] and [align] values. The [align] option can be specified as < to left justify the item, ^ to center the item, or > to right justify it. If desired, a single character can be provided as the fill to use instead of spaces. (You have to specify the alignment if you want to use fill):
Listing 11.3.2.
Again, width comes in handiest when trying to line up columns of text. To do this, it helps to come up with a plan for what your columns will look like and how you want to justify them. Say I want to print:
 4:55 | someperson       |       $20.20
12:02 | aguy             |     $1233.20
 8:14 | thatgirl         |        $1.12
My columns look like:
  • hour 2 digits, right justified
  • minutes 2 digits, right justified, fill with 0s (so 2 becomes 02)
  • A bar with spaces on either side
  • name left justified, with 16 characters of space
  • A bar with spaces
  • money, right justified, 12 spaces with 2 digits after the decimal point
To do this, I might try using the following format string:
{:>2}:{:0>2} | {:<16} | ${:>12.2f}
Notice the | characters where I want bars with spaces around them and the $ before the money placeholder. Here it is in action:
Listing 11.3.3.
Do you notice a problem? The dollar sign is not part of the number being formatted, so the extra spaces added to the money come between the $ and the digits. To fix this, I could format the money into a string first, then use that string to make the final output. While I am at it, I might make a function that does this work so it is easy to generate a line of output:
Listing 11.3.4.

Checkpoint 11.3.1.

Checkpoint 11.3.2.

You have attempted of activities on this page.