在 Ubuntu 上使用 Python 出现“乱码”,通常不是 Python 本身的问题,而是编码(encoding)不一致导致的。下面用通俗的方式给你总结常见原因和解决办法。
Ubuntu 终端默认应是 UTF-8,但有时被改成了 GBK、ISO-8859-1 等。
现象
print("中文")
显示成:
䏿–‡
解决
locale
如果不是 UTF-8,执行:
sudo apt install locales
sudo locale-gen zh_CN.UTF-8
export LANG=zh_CN.UTF-8
export LC_ALL=zh_CN.UTF-8
永久生效(写入 ~/.bashrc):
echo 'export LANG=zh_CN.UTF-8' >> ~/.bashrc
echo 'export LC_ALL=zh_CN.UTF-8' >> ~/.bashrc
Python 3 默认源码是 UTF-8,但如果你:
就会乱码或报错。
解决
# -*- coding: utf-8 -*-
这是最常见错误。
❌ 错误写法:
with open("a.txt") as f:
print(f.read())
✅ 正确写法:
with open("a.txt", encoding="utf-8") as f:
print(f.read())
写文件同理:
with open("a.txt", "w", encoding="utf-8") as f:
f.write("中文")
例如:
GBKlatin1解决 明确指定编码:
requests.get(url).content.decode("gbk")
Python 2 默认不是 UTF-8,非常容易乱码。
✅ 建议:直接用 Python 3
python3 -c "import sys; print(sys.getdefaultencoding())"
应为:
utf-8
locale
应为:
LANG=zh_CN.UTF-8
# -*- coding: utf-8 -*-
import sys
print("中文测试")
print(sys.getdefaultencoding())
你可以把具体乱码截图 / 代码 / 报错信息发出来,我可以直接帮你定位是哪一步编码错了。