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.

PythonCli Tooling

Code

pythonsnippet
17 lines
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

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`.