Python 3 將 print 從陳述式改為函式,帶來更強大的格式化、導向控制、分隔符自訂等功能。本文系統整理 print() 完整用法:基本輸出、格式化字串、進階參數(sep、end、file、flush)、實戰技巧與常見陷阱。
# 多參數自動以空格分隔
print("Hello", "World", 2024) # Hello World 2024
# 自訂分隔符 sep
print("2024", "01", "15", sep="-") # 2024-01-15
print("a", "b", "c", sep="") # abc
# 自訂結尾 end(預設換行 \n)
print("Loading", end=" ")
print("Complete") # Loading Complete
# 不換行輸出進度
for i in range(5):
print(".", end="", flush=True) # 即時輸出
print() # 最後換行
name = "Alice"
age = 25
pi = 3.1415926535
print(f"{name} is {age} years old") # Alice is 25 years old
print(f"Pi ≈ {pi:.3f}") # Pi ≈ 3.142
print(f"{pi:10.3f}") # 右對齊寬度10: 3.142
print(f"{pi:-10.3f}") # 左對齊寬度10:3.142
print(f"{age:05d}") # 零填寬度5:00025
print(f"{name:*^20}") # 置中星號填寬度20:****Alice****
print("{} is {} years old".format(name, age))
print("{n} is {a} years old".format(n=name, a=age))
print("Pi ≈ {:.3f}".format(pi))
print("{:10.3f}".format(pi))
print("{:*^20}".format(name))
print("%s is %d years old" % (name, age))
print("Pi ≈ %.3f" % pi)
print("Hex: %x, Oct: %o, Bin: %b" % (255, 255, 255))
# 注意:% 元組語法陷阱
print("Value: %s" % (42,)) # 單元素元組需加逗號
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
| 參數 | 預設值 | 說明 | 範例 |
|---|---|---|---|
| sep | ' ' | 參數間分隔符 | print(1,2,3, sep=',') → 1,2,3 |
| end | '\n' | 結尾字串 | print('A', end='') → 不換行 |
| file | sys.stdout | 輸出串流物件 | print('log', file=open('log.txt','a')) |
| flush | False | 強制立即輸出 | print('.', end='', flush=True) 進度條 |
with open("output.txt", "w", encoding="utf-8") as f:
print("Line 1", file=f)
print("Line 2", file=f)
print(1, 2, 3, sep=",", file=f) # CSV 格式
import sys
print("Warning: config not found", file=sys.stderr)
print("Error: connection failed", file=sys.stderr)
import io, contextlib
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
print("Captured output")
print(1, 2, 3)
print("Buffer content:", buf.getvalue())
lst = [1, 2, 3, "python"]
dct = {"a": 1, "b": 2}
print(lst) # [1, 2, 3, 'python']
print(dct) # {'a': 1, 'b': 2}
# 美化輸出(pprint)
import pprint
pprint.pprint({"nested": {"deep": [1,2,3]}}, width=40)
x = 42
print(f"{x=}") # x=42
print(f"{x= :05d}") # x=00042
import time, sys
for i in range(101):
bar = "█" * (i//2) + " " * (50 - i//2)
print(f"\r[{bar}] {i}%", end="", flush=True)
time.sleep(0.02)
print() # 完成換行
print 或寫入檔案,避免頻繁系統呼叫。sys.stdout.write 比 print 略快(無格式化開銷),但較不便利。Python 3 print() 函式功能強大、參數靈活。掌握 f-string 格式化、sep/end/file/flush 四大參數、輸出導向控制,能處理從簡單除錯到複雜報表、進度條、日誌系統等所有輸出需求。建議統一使用 f-string,善用 file 參數分離標準輸出/錯誤輸出,構建可維護的輸出架構。