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.
Code
# 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: 0xbeefHow 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
CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. Its state lives in module-level bindings: `rows`, `big`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.