← 中文资源

简体中文版本

textwrap 折行去缩进与截断

textwrap 三件套处理终端文本:dedent 去掉三引号块的公共缩进,fill 与 wrap 按 30 列折行,shorten 超长摘要截断并加省略号占位。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

顶层就这几处状态:usage、body。

常见问题

有语言之外需要解析的导入吗?

没有。每个导入都解析到语言自带的模块。 文件用顶层绑定保存自己的状态:usage、body。

代码示例

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=" ..."))