最近一段时间开始学习Python,或多或少的会在代码中进行中文注释或者是输出中文等。刚开始的时候我是在命令行下使用python,在编辑器下写好代码,python file.py 来运行,因而当代码中出现中文时便会出错,具体提示如下:
看了下错误提示,编码问题,那时有其他事情便不想纠结,我英语注释还行么。。。
后来使用Idle,当代码中出现中文时,F5运行便会出现提示:
看到# -*- coding: cp936 -*-注释格式引起了兴趣,便去上网搜一搜,便找到了Python官网的Python增强建议(PEPs)(实际在命令行运行时就给出了该链接,参加图1),关于编码具做了具体的阐述(http://www.python.org/dev/peps/pep-0263/):
Python will default to ASCII as standard encoding if no other
encoding hints are given.
To define a source code encoding, a magiccomment must
be placed into the source files either asfirst or second
line in the file, such as:
# coding=<encoding name>
or (using formats recognized by populareditors)
#!/usr/bin/python
# -*- coding: <encoding name>-*-
or
#!/usr/bin/python
# vim: set fileencoding=<encodingname> :
默认是ASCII,所以不指定编码则在代码中出现中文则会编译出错。
More precisely, the first or second line must match the regular expression "coding[:=]\s*([-\w.]+)".
编码指定只能在第一或者第二行,否则会被忽略而默认为ASCII,并且编码指定格式是用上述则正表达式匹配,所以在前两行的注释行(甚至可以不是注释,加下述代码,只是演示,不推荐使用)中只要有coding: <encoding name>就行了,而大家经常用的-*-只是为了美观。
code = "coding: gb2312" # 在第一行,但不是注释 str = "你好" print str
官网PEPs中关于编码有更详细的阐述,有兴趣的朋友可以自行阅读。