Python 文字換行和填充


在 Python 中,textwrap 模組用於格式化和換行純文字。有一些選項可以透過調整輸入段落中的換行符來格式化文字。

要使用這些模組,我們需要在程式碼中匯入textwrap 模組。

import textwrap

建構函式的 Textwrapper 例項屬性如下所示:

序號 屬性和描述
1

width

行的最大長度。預設值為 70

2

expand_tabs

如果此屬性的值為真,則所有制表符都將替換為空格。預設值為 True。

3

tabsize

當 expand_tabs 屬性為真時,它將幫助設定具有不同值的 tabsize。預設值為 8。

4

replace_whitespace

當值為 True 時,文字中的所有空格字元都將替換為單個空格,預設值為 True。

5

drop_whitespace

換行文字後,將刪除開頭和結尾的空格。預設值為 True。

6

initial_indent

它將給定的字串新增到換行文字的第一行的開頭。預設值為 ' '。

7

subsequent_indent

它將給定的字串新增到換行文字的所有行的開頭。預設值為 ' '。

8

placeholder

無論是否已截斷,它都會在輸出檔案的末尾追加字串。預設值為 […]。

9

max_lines

此值將確定換行後將有多少行。如果值為 None,則沒有限制。預設值為 None。

10

break_long_words

它會將長單詞拆分以適應給定的寬度。預設值為 True。

11

break_on_hyphens

它用於在複合詞的連字元後換行。預設值為 True。

文字換行方法

Textwrap 模組中有一些方法。這些模組是:

模組 (textwrap.wrap(text, width = 70, **kwargs)) -

此方法換行輸入段落。它使用行寬來換行內容。預設行寬為 70。它返回一個行列表。列表中儲存所有換行行。

模組 (textwrap.fill(text, width = 70, **kwargs)) -

fill() 方法類似於 wrap 方法,但它不會生成列表。它生成一個字串。在超過指定的寬度後,它會在後面新增換行符。

模組 (textwrap.shorten(text, width, **kwargs)) -

此方法縮短或截斷字串。截斷後,文字的長度將與指定的寬度相同。它將在字串末尾新增 […]。

示例程式碼

即時演示

import textwrap

python_desc = """Python is a general-purpose interpreted, interactive, object-oriented, 
                 and high-level programming language. It was created by Guido van Rossum 
                 during 1985- 1990. Like Perl, Python source code is also available under 
                 the GNU General Public License (GPL). This tutorial gives enough 
                 understanding on Python programming language."""

my_wrap = textwrap.TextWrapper(width = 40)
wrap_list = my_wrap.wrap(text=python_desc)

for line in wrap_list:
   print(line)
    
single_line = """Python is a general-purpose interpreted, interactive, object-oriented, 
                 and high-level programming language."""

print('\n\n' + my_wrap.fill(text = single_line))

short_text = textwrap.shorten(text = python_desc, width=150)
print('\n\n' + my_wrap.fill(text = short_text))

輸出

Python is a general-purpose interpreted,
interactive, object-oriented,
and high-level programming language. It
was created by Guido van Rossum
during 1985- 1990. Like Perl, Python
source code is also available under
the GNU General Public License (GPL).
This tutorial gives enough
understanding on Python programming
language.

Python is a general-purpose interpreted,
interactive, object-oriented,
and high-level programming language.

Python is a general-purpose interpreted,
interactive, object-oriented, and high-
level programming language. It was
created by Guido van Rossum [...]

更新於: 30-Jul-2019

5K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.