
- Python 基礎
- Python - 首頁
- Python - 概述
- Python - 歷史
- Python - 特性
- Python vs C++
- Python - Hello World 程式
- Python - 應用領域
- Python - 直譯器
- Python - 環境搭建
- Python - 虛擬環境
- Python - 基本語法
- Python - 變數
- Python - 資料型別
- Python - 型別轉換
- Python - Unicode 系統
- Python - 字面量
- Python - 運算子
- Python - 算術運算子
- Python - 比較運算子
- Python - 賦值運算子
- Python - 邏輯運算子
- Python - 位運算子
- Python - 成員運算子
- Python - 身份運算子
- Python - 運算子優先順序
- Python - 註釋
- Python - 使用者輸入
- Python - 數字
- Python - 布林值
- Python 控制語句
- Python - 控制流
- Python - 決策
- Python - if 語句
- Python - if else
- Python - 巢狀 if
- Python - match-case 語句
- Python - 迴圈
- Python - for 迴圈
- Python - for-else 迴圈
- Python - while 迴圈
- Python - break 語句
- Python - continue 語句
- Python - pass 語句
- Python - 巢狀迴圈
- Python 函式與模組
- Python - 函式
- Python - 預設引數
- Python - 關鍵字引數
- Python - 僅限關鍵字引數
- Python - 位置引數
- Python - 僅限位置引數
- Python - 可變引數
- Python - 變數作用域
- Python - 函式註解
- Python - 模組
- Python - 內建函式
- Python 字串
- Python - 字串
- Python - 字串切片
- Python - 修改字串
- Python - 字串連線
- Python - 字串格式化
- Python - 跳脫字元
- Python - 字串方法
- Python - 字串練習
- Python 列表
- Python - 列表
- Python - 訪問列表元素
- Python - 修改列表元素
- Python - 新增列表元素
- Python - 刪除列表元素
- Python - 迴圈遍歷列表
- Python - 列表推導式
- Python - 列表排序
- Python - 複製列表
- Python - 合併列表
- Python - 列表方法
- Python - 列表練習
- Python 元組
- Python - 元組
- Python - 訪問元組元素
- Python - 更新元組
- Python - 解包元組
- Python - 迴圈遍歷元組
- Python - 合併元組
- Python - 元組方法
- Python - 元組練習
- Python 集合
- Python - 集合
- Python - 訪問集合元素
- Python - 新增集合元素
- Python - 刪除集合元素
- Python - 迴圈遍歷集合
- Python - 合併集合
- Python - 複製集合
- Python - 集合運算子
- Python - 集合方法
- Python - 集合練習
- Python 字典
- Python - 字典
- Python - 訪問字典元素
- Python - 修改字典元素
- Python - 新增字典元素
- Python - 刪除字典元素
- Python - 字典檢視物件
- Python - 迴圈遍歷字典
- Python - 複製字典
- Python - 巢狀字典
- Python - 字典方法
- Python - 字典練習
- Python 陣列
- Python - 陣列
- Python - 訪問陣列元素
- Python - 新增陣列元素
- Python - 刪除陣列元素
- Python - 迴圈遍歷陣列
- Python - 複製陣列
- Python - 反轉陣列
- Python - 排序陣列
- Python - 合併陣列
- Python - 陣列方法
- Python - 陣列練習
- Python 檔案處理
- Python - 檔案處理
- Python - 寫入檔案
- Python - 讀取檔案
- Python - 重新命名和刪除檔案
- Python - 目錄
- Python - 檔案方法
- Python - OS 檔案/目錄方法
- Python - OS 路徑方法
- 面向物件程式設計
- Python - OOPs 概念
- Python - 類與物件
- Python - 類屬性
- Python - 類方法
- Python - 靜態方法
- Python - 建構函式
- Python - 訪問修飾符
- Python - 繼承
- Python - 多型
- Python - 方法重寫
- Python - 方法過載
- Python - 動態繫結
- Python - 動態型別
- Python - 抽象
- Python - 封裝
- Python - 介面
- Python - 包
- Python - 內部類
- Python - 匿名類和物件
- Python - 單例類
- Python - 包裝類
- Python - 列舉
- Python - 反射
- Python 錯誤與異常
- Python - 語法錯誤
- Python - 異常
- Python - try-except 塊
- Python - try-finally 塊
- Python - 丟擲異常
- Python - 異常鏈
- Python - 巢狀 try 塊
- Python - 使用者自定義異常
- Python - 日誌記錄
- Python - 斷言
- Python - 內建異常
- Python 多執行緒
- Python - 多執行緒
- Python - 執行緒生命週期
- Python - 建立執行緒
- Python - 啟動執行緒
- Python - 執行緒連線
- Python - 執行緒命名
- Python - 執行緒排程
- Python - 執行緒池
- Python - 主執行緒
- Python - 執行緒優先順序
- Python - 守護執行緒
- Python - 執行緒同步
- Python 同步
- Python - 執行緒間通訊
- Python - 執行緒死鎖
- Python - 中斷執行緒
- Python 網路程式設計
- Python - 網路程式設計
- Python - Socket 程式設計
- Python - URL 處理
- Python - 泛型
- Python 庫
- NumPy 教程
- Pandas 教程
- SciPy 教程
- Matplotlib 教程
- Django 教程
- OpenCV 教程
- Python 雜項
- Python - 日期與時間
- Python - 數學
- Python - 迭代器
- Python - 生成器
- Python - 閉包
- Python - 裝飾器
- Python - 遞迴
- Python - 正則表示式
- Python - PIP
- Python - 資料庫訪問
- Python - 弱引用
- Python - 序列化
- Python - 模板
- Python - 輸出格式化
- Python - 效能測量
- Python - 資料壓縮
- Python - CGI 程式設計
- Python - XML 處理
- Python - GUI 程式設計
- Python - 命令列引數
- Python - 文件字串
- Python - JSON
- Python - 傳送郵件
- Python - 擴充套件
- Python - 工具/實用程式
- Python - GUIs
- Python 高階概念
- Python - 抽象基類
- Python - 自定義異常
- Python - 高階函式
- Python - 物件內部
- Python - 記憶體管理
- Python - 元類
- Python - 使用元類進行超程式設計
- Python - 模擬和存根
- Python - Monkey Patching
- Python - 訊號處理
- Python - 型別提示
- Python - 自動化教程
- Python - Humanize 包
- Python - 上下文管理器
- Python - 協程
- Python - 描述符
- Python - 診斷和修復記憶體洩漏
- Python - 不可變資料結構
- Python 有用資源
- Python - 問答
- Python - 線上測驗
- Python - 快速指南
- Python - 參考
- Python - 速查表
- Python - 專案
- Python - 有用資源
- Python - 討論
- Python 編譯器
- NumPy 編譯器
- Matplotlib 編譯器
- SciPy 編譯器
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]}}