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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP