python 中文显示乱码如何处理

你好! 解决 Python 中文显示乱码的方法有以下几种:

  1. 在文件头添加如下代码:
# -*- coding: utf-8 -*-
  1. 在文件头添加如下代码:
#!/usr/bin/python
# -*- coding: utf-8 -*-
  1. 使用 codecs 库:
import codecs# 使用 codecs 打开文件
f = codecs.open('file.txt', 'r', 'utf-8')

# 读取文件内容
data = f.read()

# 关闭文件
f.close()
  1. 使用 sys 库和 setdefaultencoding 函数:
import sys

# 设置系统默认编码为 utf-8
reload(sys)
sys.setdefaultencoding('utf-8')

注意: 在 Python 3 中, 不能再使用 sys.setdefaultencoding 函数设置编码, 会报错。

希望这些方法能帮到你!