f-string Format Specs Align Column Output

Build aligned CLI tables with f-string format specs: left and right alignment, fixed precision, fill and center, thousands grouping, and percent rendering.

PythonCli Tooling

Code

pythonsnippet
18 lines
# f-string 的格式规格:对齐、填充、宽度、精度一次到位
rows = [
    ("orders", 1240, 12.5),
    ("refunds", 37, 0.75),
    ("signups", 8621, 104.25),
]

print(f"{'metric':<10}{'count':>8}{'rate':>10}")
for name, count, rate in rows:
    print(f"{name:<10}{count:>8}{rate:>10.2f}")

# 填充字符与居中:构造分隔线与表头
print(f"{'':=^28}")
print(f"{'summary':*^28}")

# 千分位、百分号、进制:数字呈现交给格式规格而不是手工拼串
big = 9876543
print(f"grouped: {big:,} | pct: {0.0723:.1%} | hex: {48879:#x}")

Output

Captured from a sandboxed run of this snippet in the build pipeline.

metric       count      rate
orders        1240     12.50
refunds         37      0.75
signups       8621    104.25
============================
**********summary***********
grouped: 9,876,543 | pct: 7.2% | hex: 0xbeef

How the snippet works

for name, count, rate in rows is the loop that carries the per-item work.

Top-level bindings rows, big hold the demo state — nothing sits inside a function scope.

Applying it

The demo output is labeled (grouped:), so every printed line maps back to its originating operation.

Statements that matter

for name, count, rate in rows:
    print(f"{name:<10}{count:>8}{rate:>10.2f}")

Interactive Tools for This Topic

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. Its state lives in module-level bindings: `rows`, `big`.