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.
Code
# 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 okWhat 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
Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.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
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library.
Report a problem with this exampleOpens a pre-filled issue on GitHub.