Advanced Formatting

Concepts covered: f-strings

F-strings can also pad and align values, and they control how numbers are displayed.

Alignment and padding

Control how values are positioned within a fixed width:

name = "Maya"

print(f"|{name:<10}|")
print(f"|{name:>10}|")
print(f"|{name:^10}|")
print(f"|{name:*^10}|")

Output:

|Maya      |
|      Maya|
|   Maya   |
|***Maya***|

< left-aligns, > right-aligns, ^ centers. The number specifies total width. Optional fill character (like *) pads the empty space.

Alignment specifiers

Number formatting

Format specs set decimal precision, thousands separators, explicit signs and zero padding:

pi = 3.14159265359
big_num = 1234567890
negative = -42

print(f"Pi: {pi:.4f}")
print(f"Big: {big_num:,}")
print(f"Signed: {negative:+d}")
print(f"Padded: {42:05d}")

Output:

Pi: 3.1416
Big: 1,234,567,890
Signed: -42
Padded: 00042

These produce: "Pi: 3.1416" (4 decimals), "Big: 1,234,567,890" (comma separators), "Signed: -42" (explicit sign), and "Padded: 00042" (zero-padded).

Percentage and scientific notation

ratio = 0.854
tiny = 0.00000123

print(f"Percent: {ratio:.1%}")
print(f"Scientific: {tiny:.2e}")

Output:

Percent: 85.4%
Scientific: 1.23e-06

The % format multiplies by 100 and adds the % sign. The e format uses scientific notation.

For financial applications, consider the decimal module instead of floats. Float formatting can display "0.30" but the underlying value might be 0.299999... due to floating-point precision.

F-string format specifiers follow the pattern {value:[[fill]align][sign][#][0][width][grouping][.precision][type]}. For most everyday formatting, only a few parts are needed: width for padding, .precision for decimals, , for thousands, and f or d for the type.

Number formatting in f-strings is consistent and composable. The comma and precision specifiers combine naturally: {price:,.2f} produces exactly the format used in financial reports, with thousands separated and two decimal places.

About this lesson

This section is part of the Strings: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.