# 讀取 Excel 中文 sheet 名
name_bytes = sheet.name.encode('utf-8') # str → bytes
name_str = name_bytes.decode('utf-8') # bytes → str
print(name_str)
原則:內部統一用 Unicode (str),邊界處理時顯式編解碼。Python 3 默認字符串即 Unicode,無需此操作。
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
危害:
sys.setdefaultencoding。# -*- coding: utf-8 -*-;open(..., encoding='utf-8');Content-Type 或 chardet 解碼;charset=utf8mb4);chcp 65001)。| 現象 | 原因 | 修正 |
|---|---|---|
| 打印顯示 \xe4\xb8\xad | bytes 直接打印 | .decode('utf-8') |
| 存入 MySQL 變 ??? | 連接未指定 charset | connect(charset='utf8mb4') |
| 讀取 CSV 報 UnicodeDecodeError | 文件非 UTF-8 | open(encoding='gbk') 或 chardet 檢測 |
| Windows 控制台亂碼 | 終端編碼非 UTF-8 | chcp 65001 / 使用 Windows Terminal |