python中文编码问题
第一步:在代码中输入以下命令,执行:
#在Python中显示中文注释和输出中文
a ="中文"
print a
返回错误:
d:\Python27\python.exe "D:\test\中文.py"
Process started >>>
File "D:\test\中文.py", line 1
SyntaxError: Non-ASCII character '\xe5' in file D:\test\中文.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
<<< Process finished. (Exit code 1)
================ READY ================
第二步,加入编码格式:
#-*- coding:utf-8 –*-
#在Python中显示中文注释和输出中文
a ="中文"
print a
返回结果:
d:\Python27\python.exe "D:\test\中文.py"
Process started >>>
涓枃
<<< Process finished. (Exit code 0)
================ READY ================
程序可以正确执行,但输出的仍是乱码。
第三步,查找乱码并处理:
原因:这是因为win的,命令行用的是cp936编码,而上面脚本用的是utf-8编码,因此导致乱码。
解决方法是,使用decode和encode函数对字符重新解码和编码。
#-*- coding:utf-8 –*-
#在Python中显示中文注释和输出中文
a ="中文"
print a.decode('utf-8').encode('cp936')
返回结果:
d:\Python27\python.exe "D:\test\中文.py"
Process started >>>
中文
<<< Process finished. (Exit code 0)
================ READY ================