Python菜鸟今天写程序时加了中文注释,竟然就报错了,头一回碰到注释报错,活久见。
平时看别人代码时,或多或少会碰到中文注释乱码问题,原因是不同文件编码格式,有些文件编码并不能显示中文,如ASCII。而PyCharm对于中文不仅仅是显示乱码问题,而是编译报错。如下
SyntaxError: Non-ASCII character '\xe6' in file TestPy3/t.py on line 19, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
看看提示的链接
Defining the Encoding Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=or (using formats recognized by popular editors) #!/usr/bin/python # -*- coding: -*- or #!/usr/bin/python # vim: set fileencoding= :
大概意思是,默认文件是ASCII格式,需要更改文件编码,操作是在文件首行加上
#!/usr/bin/python# -*- coding:utf8 -*-
编译运行,一切正常。