第一章:文本-textwrap:格式化文本段落-缩进块

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值