函數簽名
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
核心參數解析
| 參數 | 預設 | 說明 |
objects | — | 任意數量物件,依序轉字串 (呼叫 str()) |
sep | ' ' | 物件間分隔符 |
end | '\n' | 結尾字串,'' 可抑制換行 |
file | sys.stdout | 支援 write() 的檔案物件 |
flush | False | 立即刷新緩衝區 (即時日誌必備) |
基礎用法
>> print('Hello', 'World')
Hello World
>>> print('A', 'B', 'C', sep='|')
A|B|C
>>> print('Loading', end=' ', flush=True)
Loading >>> print('Done')
Loading Done
>>> print(1, 2, 3, sep=', ', end='.\n')
1, 2, 3.
格式化輸出:f-string (Python 3.6+) 為主流
10.3f}') # 零填充
print(f'Pi = {pi:+.3f}') # 強制正負號
print(f'Percent: {0.1234:.2%}') # 12.34%
# 進制
print(f'Dec: {255}, Hex: {255:x}, Oct: {255:o}, Bin: {255:b}')
# Dec: 255, Hex: ff, Oct: 377, Bin: 11111111
# 日期時間
from datetime import datetime
now = datetime.now()
print(f'Now: {now:%Y-%m-%d %H:%M:%S}')
舊式格式化 (仍常見於舊代碼)
導向檔案與日誌實戰
重導向 sys.stdout 捕獲輸出
常見陷阱
- 預設換行:
print(x) 總換行;用 end='' 抑制。
- 緩衝區:管道/檔案導向時預設塊緩衝,即時日誌必加
flush=True 或 -u 參數執行。
- 非字串物件:自動呼叫
str(),自訂類別實作 __str__ 控制輸出。
print 回傳 None,不可鏈式呼叫。
進階:自訂印出函數