Transferred from: http://blog.csdn.net/arbel/article/details/7957782
If you want to write Chinese in the Python2 py file, you must add a line to declare the file encoded comments, otherwise python2 will use ASCII encoding by default.
[Python]View Plaincopy
- #-*-Coding:utf-8-*-
The question comes, why do you declare it?
First please refer to THE PEP http://www.python.org/dev/peps/pep-0263/of Python
The summary is as follows
1. The code note must be placed on the first or second line
2. The optional format is
[Python]View Plaincopy
- # coding=<encoding Name>
[Python]View Plaincopy
- #!/usr/bin/python
- #-*-Coding: <encoding name>-*-
[Python]View Plaincopy
- #!/usr/bin/python
- # Vim:set fileencoding=<encoding name>:
But looking down, it turns out that as long as the annotations have coding and corresponding codes,
[Python]View Plaincopy
- #!/usr/bin/python
- # Vim:set fileencoding=<encoding name>:
So it's been a bit confusing to have the most standard way of doing it.
Later thought, looked under the vim of the Python syntax highlighting file, the following regular expression is identified as the code declaration
[Plain]View Plaincopy
- \%^.*\ (\n.*\) \?#.*coding[:=]\s*[0-9a-za-z-_. \+.*$
For this regular is somewhat not understand, but the following must have coding:[code] or coding=[code], this should be considered as the standard way of declaring it.
But why is this usually the way it is?
[Python]View Plaincopy
- #-*-Coding:utf-8-*-
The answer is mentioned in PEP-0263, that is, Emacs and other editors use this way to encode the declaration.
There are a lot of things in Pep that are worth referencing, after all, you can tell why the program is designed like this.
Code comment for Python #-*-Coding:utf-8-*-