1.2.5 缩进块
可以使用indent()函数为一个字符串找那个的所有行增加一致的前缀文本。这个例子会格式化通用的示例文本,就好像它是回复邮件中所引用的原email的一部分,这里使用>作为每一行的前缀。
import textwrap
from textwrap_example import sample_text
dedented_text = textwrap.dedent(sample_text)
wrapped = textwrap.fill(dedented_text,width=50)
wrapped += '\n\nSecond paragraph after a blank line.'
final = textwrap.indent(wrapped,'>')
print('Quoted block:\n')
print(final)
文本块按换行符分解,将为包含文本的各行增加前缀,然后再把这些行合并为一个新字符串并返回。
运行结果:
为了控制哪些行接受新前缀,可以传入一个callable对象作为indent()的predicate参数。会依次为各行文本调用这个callable,并为返回值为true的行添加前缀。
import textwrap
from textwrap_example import sample_text
def should_indent(line):
print('Indent{!r}?'.format(line))
return len(line.strip()) % 2 == 0
dedented_text = textwrap.dedent(sample_text)
wrapped = textwrap.fill(dedented_text,width=50)
final = textwrap.indent(wrapped,'EVEN ',predicate=should_indent)
print('\nQuoted block:\n')
print(final)
运行结果:
Indent’ The textwrap module can be used to format text\n’?
Indent’for output in situations where pretty-printing is\n’?
Indent’desired. It offers programmatic functionality\n’?
Indent’similar to the paragraph wrapping or filling\n’?
Indent’features found un many text editors.’?
Quoted block:
EVEN The textwrap module can be used to format text
for output in situations where pretty-printing is
desired. It offers programmatic functionality
EVEN similar to the paragraph wrapping or filling
EVEN features found un many text editors.