首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 3 Print 函式完整教學:格式化輸出、進階參數與最佳實務

     編輯:更多程式設計知識

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()  # 最後換行

格式化輸出三大方式

1. f-string(Python 3.6+ 推薦)


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****

2. str.format()(Python 2.7+ / 3.0+)


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))

3. % 格式化(舊式,相容性用)


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='') → 不換行
filesys.stdout輸出串流物件print('log', file=open('log.txt','a'))
flushFalse強制立即輸出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)

自訂串流(如 io.StringIO 捕獲輸出)


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)

變數名與值同時顯示(Python 3.8+ = 語法)


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()  # 完成換行

常見陷阱與避坑指南

  1. print 為函式需加括號:Python 2 `print "hi"` → Python 3 `print("hi")`。
  2. % 元組語法:`print("%s %s" % a, b)` 錯誤,正確 `print("%s %s" % (a, b))`。
  3. 預設空格分隔:`print(a, b)` 中間有空格,無空格用 `sep=""`。
  4. flush=True 影響效能:大量輸出時僅關鍵點啟用。
  5. 編碼問題:Windows 主控台預設 cp950,輸出中文需設定 `chcp 65001` 或使用 `encoding="utf-8"` 開啟檔案。

效能考量

  • 大量輸出建議累積字串一次 print 或寫入檔案,避免頻繁系統呼叫。
  • sys.stdout.write 比 print 略快(無格式化開銷),但較不便利。
  • 格式化:f-string > format > % (速度與可讀性綜合)。

總結

Python 3 print() 函式功能強大、參數靈活。掌握 f-string 格式化、sep/end/file/flush 四大參數、輸出導向控制,能處理從簡單除錯到複雜報表、進度條、日誌系統等所有輸出需求。建議統一使用 f-string,善用 file 參數分離標準輸出/錯誤輸出,構建可維護的輸出架構。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved