center Pads Both Sides With a Fill Character

Center strings in a fixed width with str.center, which splits leftover padding between the sides, rejects multi-character fills, and never truncates.

PythonCli Tooling

Code

pythonsnippet
16 lines
# center 在两侧补齐,ljust/rjust 只补一侧
for word in ["OK", "WARN", "ERROR"]:
    print(word.center(10, "."))

# 填充字符必须是单字符,多字符会报错
try:
    "x".center(5, "--")
except TypeError as e:
    print("error:", e)

# 超过目标宽度时不截断,原样返回
print("very-long-label".center(8))

# 配合 ljust/rjust 做表头对齐
print("name".center(8) + "status".center(10))
print("api".center(8) + "ok".center(10))

Output

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

....OK....
...WARN...
..ERROR...
error: The fill character must be exactly one character long
very-long-label
  name    status  
  api       ok

What runs and in what order

Iteration happens inside for word in ["OK", "WARN", "ERROR"] — everything outside it runs once.

Points of care

  • No package manager involved — every call resolves to a built-in API.

Applying it

The run prints error:, very-long-label, name — each prefix names the step that produced it.

Statements that matter

except TypeError as e:
    print("error:", e)

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library.