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.

PythonCli Tooling

Code

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

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