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.