实现说明
顶层就这几处状态: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=" ..."))