Python 程序将文本包装成宽度为 w 的段落


假设我们有字符串 s 和宽度 w。我们需要将文本包装成宽度为 w 的段落。这可以使用 textwrap 库中的 fill() 函数轻松完成。因此,我们必须先导入 textwrap 库。

因此,如果输入为 s = "The quick brown fox jumps over the lazy dog" w = 9,则输出将为

The quick

brown fox

jumps

over the

lazy dog

为解决此问题,我们将按照以下步骤操作 -

  • 将字符串存储到 s 中

  • 将宽度存储到 w 中

  • 通过传递 s 作为第一个参数,将 w 作为第二个参数,调用 textwrap.fill(s,w)

示例

让我们看看以下实现,以加深理解

import textwrap
def solve(s, w):
   return textwrap.fill(s, w)

s = "The quick brown fox jumps over the lazy dog"
w = 9
print(solve(s, w))

输入

"The quick brown fox jumps over the lazy dog", 9

输出

The quick
brown fox
jumps
over the
lazy dog

更新于:2021 年 10 月 11 日

842 次浏览

开启职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.