ljust rjust zfill Align Report Columns
ljust and rjust pad strings to a fixed width for aligned report columns, while zfill zero-fills numeric codes so 7 becomes 000007.
Code
services = [
("api-gateway", 12, 0.99),
("billing", 3, 1.0),
("auth", 47, 0.42),
]
# ljust 左对齐、rjust 右对齐:把三列对齐到固定宽度
print("service".ljust(14), "calls".rjust(6), "share".rjust(6))
for name, calls, share in services:
print(name.ljust(14), str(calls).rjust(6), f"{share:.2f}".rjust(6))
# zfill 从左侧补 0:编号与文件名补齐固定位数
for code in ["7", "42", "1337"]:
print(code.zfill(6))
# 超过目标宽度的字符串不会被截断,原样返回
print("billing-very-long-name".ljust(14) + "|")Output
Captured from a sandboxed run of this snippet in the build pipeline.
service calls share
api-gateway 12 0.99
billing 3 1.00
auth 47 0.42
000007
000042
001337
billing-very-long-name|How it works
The loop for name, calls, share in services is the only repeated construct, unpacking one tuple per row.
One top-level binding, services, feeds the whole demo — the file defines no functions at all.
Applying it
Running the file prints labeled results such as service, billing-very-long-name — the padding behaviour is visible directly in those lines.
Statements that matter
for name, calls, share in services:
print(name.ljust(14), str(calls).rjust(6), f"{share:.2f}".rjust(6))
for code in ["7", "42", "1337"]:
print(code.zfill(6))
Interactive Tools for This Topic
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.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.
FAQ
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. Its state lives in module-level bindings: `services`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.