悬挂缩进
不仅可以设置输出的宽度,还可以采用同样的方式单独控制首行的缩进,使首行的缩进不同于后续的各行。
新建textwrap_hanging_indent.py Python文件,在里面编写如下代码,查看输出结果。
import textwrap
from textwrap_example import sample_text
dedent_text = textwrap.dedent(sample_text).strip()
print(textwrap.fill(dedent_text,
initial_indent="",
subsequent_indent=" " * 4,
width=50,
))
以上代码输出结果为:
The textwrap module can be used to format text for
output in situations where pretty-printing is
desired. It offers programmatic functionality
similar to the paragraph wrapping or filling
features found in many text editors.
以上代码允许生成悬挂缩进,即首行缩进小于其他行的缩进。
缩进也可以包含非空白字符。例如,悬挂缩进可以加前缀*来生成圆点项目符号