在 Ubuntu 下 Python 出现“乱码”,通常是编码不一致导致的(文件编码、终端编码、Python 内部编码、系统 locale 不匹配)。下面按「最常见原因 → 解决办法」给你一套实用方案。
典型表现:
???? 或 \xe4\xb8\xadUnicodeDecodeError / UnicodeEncodeErrorlocale
如果看到:
LANG=C
LC_ALL=C
或含有 POSIX,就会很容易乱码。
修复:
sudo apt update
sudo apt install locales
sudo locale-gen zh_CN.UTF-8
sudo update-locale LANG=zh_CN.UTF-8
然后重新登录或重启终端。
在 .py 文件第一行或第二行加:
# -*- coding: utf-8 -*-
(Python 3 默认就是 UTF-8,但老代码/混用环境仍建议写)
如果你用:
右键 → 首选项 → 编码 → UTF-8UTF-8set encoding=utf-8
set fileencoding=utf-8
❌ 错误:
open("a.txt")
✅ 正确:
open("a.txt", encoding="utf-8")
import sys
print(sys.stdout.encoding)
如果不是 UTF-8:
export PYTHONIOENCODING=utf-8
export LANG=zh_CN.UTF-8
pd.read_csv("x.csv", encoding="utf-8")
# 或
pd.read_csv("x.csv", encoding="gbk")
r.encoding = r.apparent_encoding
print(r.text)
echo $LANG; python3 -c "import sys; print(sys.stdout.encoding)"
如果你愿意,可以把:
发出来,我可以直接帮你“精准治乱码”。