萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 2 中文輸出亂碼解決:encode/decode 與 setdefaultencoding

本文針對 Python 2 環境(已停止維護),說明中文輸出亂碼的兩種常見解法。Python 3 預設 Unicode,無此問題。

問題背景

Python 2 預設字串為位元組串 (str),中文輸出需正確編碼/解碼,否則出現 UnicodeEncodeError 或亂碼。

方法一:顯式 encode / decode

# -*- coding: utf-8 -*-
import xlrd

filename = 'data.xls'
book = xlrd.open_workbook(filename)
for sheet in book.sheets():
    # sheet.name 為 unicode 或 bytes,視 xlrd 版本而定
    name = sheet.name
    if isinstance(name, bytes):
        print(name.decode('utf-8'))
    else:
        print(name.encode('utf-8'))  # 若為 unicode,輸出時編碼為 utf-8

原則:內部統一用 unicode (u'...'),輸出時 .encode('utf-8'),輸入時 .decode('utf-8')。

方法二:修改預設編碼 (不推薦)

# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')  # 僅 Python 2 有效,且極度不推薦

副作用: 破壞模組相容性、隱藏編碼錯誤、第三方庫行為不可預期。僅作為臨時測試用。

最佳實踐 (Python 2)

  1. 檔案開頭宣告 # -*- coding: utf-8 -*-。
  2. 字串字面值加 u 前綴:u'中文'。
  3. 讀寫檔案用 codecs.open(path, 'r', 'utf-8') 或 io.open。
  4. 標準輸出重導向:sys.stdout = codecs.getwriter('utf-8')(sys.stdout)。

遷移建議

全面升級至 Python 3.8+,原生 Unicode 支援、print 函數、型別提示、f-string 等現代特性大幅減少編碼困擾。

copyright © 萬盛學電腦網 all rights reserved