Python 程序将文本换行成宽度为 w 的段落

pythonserver side programmingprogramming更新于 2025/12/19 3:24:17

假设我们有一个字符串 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

  • 调用 textwrap.fill(s, w),将 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

相关文章


有用资源