第一步:在代码中输入如下命令,执行:python
#在Python中显示中文注释和输出中文
a ="中文"
print a函数
返回错误:post
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 ================编码
第二步,加入编码格式:spa
#-*- coding:utf-8 –*-命令行
#在Python中显示中文注释和输出中文
a ="中文"
print acode
返回结果:blog
d:\Python27\python.exe "D:\test\中文.py"
Process started >>>
涓枃
<<< Process finished. (Exit code 0)
================ READY ================utf-8
程序能够正确执行,但输出的还是乱码。it
第三步,查找乱码并处理:
缘由:这是由于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 ================