2025 Python Output 完全指南 | 從入門到高手必懂的技巧!


Python Output(輸出) 是程式設計中最基礎且不可或缺的一部分。無論你是在撰寫簡單的腳本,還是開發複雜的應用程式,如何有效地輸出與展示資訊,都是決定程式碼可讀性與專業度的關鍵。

從基本的文字輸出到格式化複雜的資料結構,熟練掌握 Python 的輸出技巧不僅能讓你的程式碼更加清晰,也能提升維護與除錯的效率。我們將深入探討 Python 的各種輸出方式,包括 f-strings(格式化字串)str.format() 方法手動格式化技巧,以及 舊式的 % 運算子格式化。你將學習如何控制輸出格式、對齊文本、設定小數點精度,並處理常見的特殊字元。

Python Output

Python Output 基礎輸出:print() 函數

基本用法 :

print() 是 Python 中最常用的輸出函數,它可以將內容輸出到終端或文件中。

print("Hello, World!")

輸出多個變數 :

你可以使用逗號分隔多個變數,print() 會自動在它們之間加上空格。

name = "Alice"
age = 25
print("Name:", name, "Age:", age)

格式化輸出 :

Python 提供了多種格式化輸出的方式,例如 f-stringformat()% 運算符。

  • f-string(推薦使用):
  print(f"Name: {name}, Age: {age}")
  • format()
  print("Name: {}, Age: {}".format(name, age))
  • % 運算符
  print("Name: %s, Age: %d" % (name, age))

進階輸出技巧

控制輸出格式 :

  • 換行與不換行
    默認情況下,print() 會在輸出後自動換行。如果你不希望換行,可以通過 end 參數來控制。
  print("Hello", end=" ")
  print("World!")
  • 分隔符
    使用 sep 參數可以自定義多個變數之間的分隔符。
  print("2025", "01", "01", sep="-")

輸出到文件 :

除了輸出到終端,print() 還可以將內容輸出到文件中。

with open("output.txt", "w") as f:
    print("Hello, File!", file=f)

輸出顏色與樣式 :

在終端中輸出帶有顏色或樣式的文字,可以使用第三方庫如 coloramatermcolor

from termcolor import colored
print(colored("Hello, World!", "red", "on_white"))

高手必懂的輸出技巧

使用 logging 模組 :

對於需要記錄日誌的應用,logging 模組比 print() 更為強大和靈活。

import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is an info message.")

輸出 JSON 數據 :

在處理 API 或數據交換時,輸出 JSON 格式的數據非常常見。

import json
data = {"name": "Alice", "age": 25}
print(json.dumps(data, indent=4))

動態輸出進度條 :

對於長時間運行的任務,可以使用 tqdm 庫來顯示進度條。

from tqdm import tqdm
import time

for i in tqdm(range(100)):
    time.sleep(0.1)

輸出表格數據 :

使用 tabulate 庫可以輕鬆輸出表格形式的數據。

from tabulate import tabulate
data = [["Alice", 25], ["Bob", 30], ["Charlie", 35]]
print(tabulate(data, headers=["Name", "Age"]))

實戰應用

輸出調試信息 :

在開發過程中,輸出調試信息是必不可少的。你可以通過條件判斷來控制調試信息的輸出。

DEBUG = True

def debug_print(message):
    if DEBUG:
        print(f"[DEBUG] {message}")

debug_print("This is a debug message.")

輸出性能數據 :

使用 time 模組可以輸出程式運行的時間,幫助你進行性能優化。

import time

start_time = time.time()

end_time = time.time()
print(f"Execution time: {end_time - start_time:.2f} seconds")

結論

Python 的 Output(輸出)功能遠比表面上看起來更加強大和靈活。從基礎的 print() 到進階的 logging、JSON 輸出、進度條和表格數據,掌握這些技巧將讓你在開發過程中更加得心應手。

希望這份 2025 Python 輸出完全指南能幫助你從入門到高手,全面提升你的 Python 技能!