在Python中使用UTF-8编码,您可以通过以下几种方法来确保程序正确处理包含非ASCII字符的文本:
在文件开头添加编码声明
在Python源代码文件的开头添加以下注释行来声明文件的编码为UTF-8:
-*- coding: utf-8 -*-
修改默认编码 (不推荐,仅适用于Python 2.x):
在Python安装目录的`site-packages`文件夹下创建一个名为`sitecustomize.py`的文件,并添加以下代码:
-*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
然后重启Python解释器。
显式指定编码
在处理字符串时,显式地指定编码和解码操作,例如:
创建一个字节字符串
byteString = "hello world! (in my default locale)"
创建一个Unicode字符串
unicodeString = u"hello Unicode world!"
将字节字符串转成Unicode字符串
s = byteString.decode('utf-8')
将Unicode字符串转回字节字符串
backToBytes = s.encode('utf-8')
检查默认编码
使用`sys.getdefaultencoding()`查看当前Python解释器的默认编码,确保它是UTF-8。
import sys
print(sys.getdefaultencoding())
处理Unicode字符串
在Python 3.x中,所有字符串默认都是Unicode字符串,不需要像Python 2.x那样显式地指定编码。
print("你好,世界!")
请根据您的Python版本和需求选择合适的方法。