textwrap Wraps Dedents And Shortens Text
Format terminal text with textwrap: dedent triple-quoted blocks, fill or wrap at a fixed width, and shorten long summaries with an ellipsis placeholder.
Code
import textwrap
# dedent: 去掉三引号块的公共缩进,模板字符串不必顶格写
usage = textwrap.dedent("""\
Usage: report.py [--width N] FILE
Render FILE as a fixed-width text report.
""")
print(usage)
# fill: 按 30 列折行直接返回整段;wrap 返回行列表
body = "The exporter streams records, validates each row, and writes the artifact."
print(textwrap.fill(body, width=30))
print([len(line) for line in textwrap.wrap(body, width=30)])
# shorten: 超长摘要截断并加占位符,保证不超过指定宽度
print(textwrap.shorten(body, width=40, placeholder=" ..."))Output
Captured from a sandboxed run of this snippet in the build pipeline.
Usage: report.py [--width N] FILE
Render FILE as a fixed-width text report.
The exporter streams records,
validates each row, and writes
the artifact.
[29, 30, 13]
The exporter streams records, ...How it works
The file’s state is a handful of top-level bindings: usage, body.
textwrap.dedent strips the common leading indentation from the triple-quoted usage block so it prints flush left. fill(body, width=30) returns one string broken at 30 columns, while wrap returns the line list — the run shows lengths [29, 30, 13]. shorten(body, width=40, placeholder=" ...") cuts the sentence to The exporter streams records, ..., fitting the placeholder within the width.
Interactive Tools for This Topic
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.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. Its state lives in module-level bindings: `usage`, `body`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.