本文針對 Python 2 環境(已停止維護),說明中文輸出亂碼的兩種常見解法。Python 3 預設 Unicode,無此問題。
Python 2 預設字串為位元組串 (str),中文輸出需正確編碼/解碼,否則出現 UnicodeEncodeError 或亂碼。
# -*- 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 有效,且極度不推薦
副作用: 破壞模組相容性、隱藏編碼錯誤、第三方庫行為不可預期。僅作為臨時測試用。
# -*- coding: utf-8 -*-。u 前綴:u'中文'。codecs.open(path, 'r', 'utf-8') 或 io.open。sys.stdout = codecs.getwriter('utf-8')(sys.stdout)。全面升級至 Python 3.8+,原生 Unicode 支援、print 函數、型別提示、f-string 等現代特性大幅減少編碼困擾。