First, when we write a Python code file, the file itself takes an encoding format, such as Utf-8 or GBK
At this point we need to set the encoding format of the file at the beginning of the Python file to tell the compiler.
If the encoding format of the file is Utf-8, the first line of the file needs to add the following statement
#coding =utf-8
If the encoding format of the file is Utf-8, the first line of the file needs to add the following statement
#coding =GBK
If the format is set to Utf-8, the Linux execution, the Chinese processing, including the display does not have any problems.
However, if the format is set to Utf-8, under window, when executed under the command line, it is found that printing Chinese with print is garbled.
The reason is because, although the file is declared as Utf-8, the source file is saved with Utf-8 encoding. But the local default encoding for Windows (www.111cn.net) is cp936, which is GBK encoding, so printing utf-8 strings directly in the console is garbled. Note that, in fact, only display problems, warehousing and other processing is not a problem.
There are two kinds of solutions.
I. Programme I:
To change the encoding format of the file to GBK, and to change the first line of the file to #coding=gbk, then there is no problem with Chinese.
But the problem with this scenario is that if the file is placed under Linux it may show a problem. Because there is no GBK character set under the General Linux machine.
II. Programme II
The file is still encoded with Utf-8, and the first line of the file header is still #coding=utf-8
At this point in print Chinese need to encode, code such as:
Print "Chinese". Decode (' Utf-8 '). Encode (sys.getfilesystemencoding ())
Note: Because the SYS module is used, you need to add the import sys in the statement execution
As a result of this problem, the print statement is bloated and can be considered in its own package.
Python 2.7 Learning Notes Chinese processing