Python - 輸出格式化



Python 中的輸出格式化

Python 中的輸出格式化用於使程式碼更易讀,輸出更友好。無論您是顯示簡單的文字字串、複雜的資料結構還是建立報表,Python 都提供了幾種格式化輸出的方法。

這些方法包括使用:

  • 字串模運算子 (%)
  • format() 方法
  • f-字串(格式化字串字面量)
  • 模板字串

此外,Python 的 "textwrap" 和 "pprint" 模組提供了高階功能,用於換行文字和漂亮列印資料結構。

使用字串模運算子 (%)

我們可以使用字串模運算子 % 來格式化輸出。此運算子是字串獨有的,彌補了缺少來自 C 的 printf() 系列函式的不足。格式說明符,如 %d%c%f%s,用作字串中的佔位符,類似於 C 中的佔位符。

下面是一個簡單的例子:

print ("My name is %s and weight is %d kg!" % ('Zara', 21))

它將產生以下輸出

My name is Zara and weight is 21 kg!

使用 format() 方法

我們可以使用 format() 方法格式化輸出,該方法在 Python 3.0 中引入,並已向後移植到 Python 2.6 和 2.7。

format() 方法是內建字串類的一部分,允許進行復雜的變數替換和值格式化。與字串模運算子相比,它被認為是一種更優雅、更靈活的格式化字串的方法。

語法

format() 方法的一般語法如下:

str.format(var1, var2,...)

返回值

該方法返回一個格式化後的字串。

字串本身包含佔位符 {},變數的值將依次插入其中。

示例

name="Rajesh"
age=23
print ("my name is {} and my age is {} years".format(name, age))

它將產生以下輸出

my name is Rajesh and my age is 23 years

您可以將變數作為關鍵字引數用於 format() 方法,並在字串中使用變數名作為佔位符。

print ("my name is {name} and my age is {age}
years".format(name="Rajesh", age=23))

使用 F-字串

F-字串或格式化字串字面量是 Python 中一種簡單、快速且易於閱讀的格式化字串的方法。您可以透過在字串的開頭引號前新增一個f來建立 f-字串。

在字串內,您可以包含變數的佔位符,這些佔位符用花括號{}括起來。這些變數的值將插入到字串的這些位置。

示例

在這個例子中,變數 "name" 和 "age" 被插入到字串中 "{name}" 和 "{age}" 所在的位置。F-字串使在字串中包含變數值變得很容易,無需使用 format() 方法或字串連線 −

name = 'Rajesh'
age = 23

fstring = f'My name is {name} and I am {age} years old'
print (fstring)

它將產生以下輸出

My name is Rajesh and I am 23 years old

Python中的格式轉換規則

你也可以指定 C 風格的格式化符號。唯一的區別是使用:代替%。例如,用{:s}代替%s,用{:d}代替%d,如下所示−

name = "Rajesh"
age = 23
print("my name is {:s} and my age is {:d} years".format(name, age))

你將得到如下所示的輸出−

my name is Rajesh and my age is 23 years

模板字串

string模組中的Template類提供了一種動態格式化字串的替代方法。Template類的優點之一是可以自定義格式化規則。

一個有效的模板字串或佔位符由兩部分組成:$符號後跟一個有效的Python識別符號。

你需要建立一個Template類的物件,並將模板字串作為引數傳遞給建構函式。接下來,呼叫Template類的substitute()方法。它將作為引數提供的數值放在模板字串的位置。

示例

from string import Template

temp_str = "My name is $name and I am $age years old"
tempobj = Template(temp_str)
ret = tempobj.substitute(name='Rajesh', age=23)
print (ret)

它將產生以下輸出

My name is Rajesh and I am 23 years old

textwrap模組

Python 的 textwrap 模組中的 wrap 類包含用於透過調整輸入段落中的換行符來格式化和換行純文字的功能。它有助於使文字格式良好且美觀。

textwrap 模組具有以下便捷函式−

textwrap.wrap(text, width=70)

textwrap.wrap() 函式換行 text(字串)中的單個段落,因此每行的長度最多為 width 個字元。返回輸出行的列表,不包含最終換行符。可選關鍵字引數對應於 TextWrapper 的例項屬性。width 預設為 70。

textwrap.fill(text, width=70)

textwrap.fill() 函式換行 text 中的單個段落,並返回包含換行段落的單個字串。

這兩種方法都在內部建立一個 TextWrapper 類物件並在其上呼叫單個方法。由於例項不會被重用,因此建立你自己的 TextWrapper 物件會更高效。

示例

import textwrap

text = '''
Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation via the off-side rule.

Python is dynamically typed and garbage-collected. It supports multiple programming paradigms, including structured (particularly procedural), object-oriented and functional programming. It is often described as a "batteries included" language due to its comprehensive standard library.
'''

wrapper = textwrap.TextWrapper(width=40)
wrapped = wrapper.wrap(text = text)

# Print output
for element in wrapped:
   print(element)

它將產生以下輸出

Python is a high-level, general-purpose
programming language. Its design
philosophy emphasizes code readability
with the use of significant indentation
via the off-side rule. Python is
dynamically typed and garbage-collected.
It supports multiple programming
paradigms, including structured
(particularly procedural), objectoriented and functional programming. It
is often described as a "batteries
included" language due to its
comprehensive standard library.

TextWrapper 物件定義了以下屬性−

  • width − (預設值:70)換行行的最大長度。

  • expand_tabs − (預設值:True)如果為真,則文字中的所有制表符都將使用 text 的 expandtabs() 方法擴充套件為空格。

  • tabsize − (預設值:8)如果 expand_tabs 為真,則文字中的所有制表符都將擴充套件為零個或多個空格,具體取決於當前列和給定的製表符大小。

  • replace_whitespace − (預設值:True)如果為真,則在製表符擴充套件之後但在換行之前,wrap() 方法將用單個空格替換每個空格字元。

  • drop_whitespace − (預設值:True)如果為真,則會刪除每行開頭和結尾的空格(換行後但在縮排之前)。但是,如果後面跟著非空格,則不會刪除段落開頭的空格。如果被刪除的空格佔據整行,則整行都會被刪除。

  • initial_indent − (預設值:'')將預先新增到換行輸出第一行的字串。

  • subsequent_indent − (預設值:'')將預先新增到換行輸出所有行(第一行除外)的字串。

  • fix_sentence_endings − (預設值:False)如果為真,則 TextWrapper 嘗試檢測句子結尾並確保句子始終用兩個空格隔開。這通常對於等寬字型中的文字是需要的。

  • break_long_words − (預設值:True)如果為真,則長於 width 的單詞將被拆分,以確保沒有行的長度超過 width。如果為假,則長單詞不會被拆分,並且某些行的長度可能超過 width。

  • break_on_hyphens − (預設值:True)如果為真,則換行最好在空格處和複合詞中的連字元之後進行,這在英語中很常見。如果為假,則只有空格會被視為潛在的良好換行位置。

shorten() 函式

shorten() 函式摺疊並截斷給定的文字以適應給定的寬度。文字首先壓縮其空格。如果隨後適合 *width*,則按原樣返回。否則,將盡可能多的單詞連線起來,然後附加佔位符 −

示例

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)

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 [...]

pprint 模組

Python 標準庫中的pprint模組使 Python 資料結構的外觀更美觀。pprint 代表 pretty printer(漂亮印表機)。任何可以被 Python 直譯器正確解析的資料結構都會被優雅地格式化。

格式化的表示式儘可能保持在一行中,但如果長度超過格式化的寬度引數,則會換成多行。pprint 輸出的一個獨特之處在於,字典在顯示錶示形式格式化之前會自動排序。

PrettyPrinter 類

pprint 模組包含PrettyPrinter類的定義。其建構函式採用以下格式−

語法

pprint.PrettyPrinter(indent, width, depth, stream, compact)

引數

  • indent − 定義每個遞迴級別新增的縮排。預設為 1。

  • width − 預設值為 80。所需的輸出受此值限制。如果長度大於 width,則將其分成多行。

  • depth − 控制要列印的級別數。

  • stream − 預設情況下為 std.out − 預設輸出裝置。它可以採用任何流物件,例如檔案。

  • compact − 預設情況下設定為 False。如果為真,則只顯示可在 width 內調整的資料。

PrettyPrinter 類定義了以下方法−

pprint() 方法

pprint() 方法列印 PrettyPrinter 物件的格式化表示形式。

pformat() 方法

pformat() 方法根據建構函式的引數返回物件的格式化表示形式。

示例

以下示例演示了 PrettyPrinter 類的簡單用法−

import pprint
students={"Dilip":["English", "Maths", "Science"],"Raju":{"English":50,"Maths":60, "Science":70},"Kalpana":(50,60,70)}
pp=pprint.PrettyPrinter()
print ("normal print output")
print (students)
print ("----")
print ("pprint output")
pp.pprint(students)

輸出顯示了普通列印和漂亮列印−

normal print output
{'Dilip': ['English', 'Maths', 'Science'], 'Raju': {'English': 50, 'Maths': 60, 'Science': 70}, 'Kalpana': (50, 60, 70)}
----
pprint output
{'Dilip': ['English', 'Maths', 'Science'],
 'Kalpana': (50, 60, 70),
 'Raju': {'English': 50, 'Maths': 60, 'Science': 70}}

pprint模組還定義了與 PrettyPrinter 方法對應的便捷函式 pprint() 和 pformat()。下面的示例使用 pprint() 函式。

from pprint import pprint
students={"Dilip":["English", "Maths", "Science"],
   "Raju":{"English":50,"Maths":60, "Science":70},
      "Kalpana":(50,60,70)}
print ("normal print output")
print (students)
print ("----")
print ("pprint output")
pprint (students)

使用 pformat() 方法的示例

下一個示例使用 pformat() 方法和 pformat() 函式。要使用 pformat() 方法,首先要設定 PrettyPrinter 物件。在這兩種情況下,格式化的表示形式都使用普通的 print() 函式顯示。

import pprint
students={"Dilip":["English", "Maths", "Science"],
   "Raju":{"English":50,"Maths":60, "Science":70},
      "Kalpana":(50,60,70)}
print ("using pformat method")
pp=pprint.PrettyPrinter()
string=pp.pformat(students)
print (string)
print ('------')
print ("using pformat function")
string=pprint.pformat(students)
print (string)

以下是上述程式碼的輸出−

using pformat method
{'Dilip': ['English', 'Maths', 'Science'],
 'Kalpana': (50, 60, 70),
 'Raju': {'English': 50, 'Maths': 60, 'Science': 70}}
------
using pformat function
{'Dilip': ['English', 'Maths', 'Science'],
 'Kalpana': (50, 60, 70),
 'Raju': {'English': 50, 'Maths': 60, 'Science': 70}}

漂亮列印也可以與自定義類一起使用。在類中重寫 __repr__() 方法。當使用 repr() 函式時會呼叫 __repr__() 方法。它是 Python 物件的官方字串表示形式。當我們使用物件作為 print() 函式的引數時,它會列印 repr() 函式的返回值。

示例

在這個例子中,__repr__() 方法返回 player 物件的字串表示形式−

import pprint
class player:
   def __init__(self, name, formats=[], runs=[]):
      self.name=name
      self.formats=formats
      self.runs=runs
   def __repr__(self):
      dct={}
      dct[self.name]=dict(zip(self.formats,self.runs))
      return (repr(dct))

l1=['Tests','ODI','T20']
l2=[[140, 45, 39],[15,122,36,67, 100, 49],[78,44, 12, 0, 23, 75]]
p1=player("virat",l1,l2)
pp=pprint.PrettyPrinter()
pp.pprint(p1)

以上程式碼的輸出為−

{'virat': {'Tests': [140, 45, 39], 'ODI': [15, 122, 36, 67, 100, 49],
'T20': [78, 44, 12, 0, 23, 75]}}
廣告