These two days, I am entangled in a piece of code. After a thorough solution, I will sort out the problems I encountered earlier, clarify my thoughts, and discover any errors on the Internet.
1. Source Code Level
REF: PEP 0263 -- Defining Python Source Code Encodings
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
The source code level refers to the type of encoding used as the source code in the. py file.
By default, like the operating system, the simplest ASCII code is used. After a Chinese annotation is used, the following questions are prompted:
SyntaxError: Non-ASCII character '\ xe5' in file test. py on line 5, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
In this case, you need to set the encoding language of the file. The best method is:
#-*-Coding: UTF-8 -*-
I think when I see this line of code, it will look at the beauty of the feeling.
Let's look at it like this .. # Coding: UTF-8
In this way, there is no problem in using Chinese at the source code level. We can easily use the interpreter.
2. Code Storage Level
Having stayed in linux for a long time, there will be a drawback, with little attention to irrelevant things. Writing a code UTF-8 will be done.
With ultra suddenly found that the original UTF-8 has a bomb, it is likely that the sky drops a large bomb, the code will become invalid :)
Reference A Very Good introduction: http://www.cnblogs.com/DDark/archive/2011/11/28/2266085.html on the impact of bom on files
In general, in windows, bom will insert its own signature at the beginning.
Therefore, if you want to use this script in linux, save it as a universal UTF-8 no bomb!
3. code execution level
Info = "starting..." Or info = u "starting ..."
Here, you only need to keep in mind-the string will be converted to a unicode object during compilation.
That is, strings are no longer saved in the source code format.
Those that do not contain u are stored in the original format. The original format here is exactly the source code-level encoding format mentioned in the first part.
The subsequent execution involves the runtime environment encoding,
You can use sys. getdefaultencoding () to view the encoding of the current running environment.
Use reload (sys)
Sys. setdefaultencoding ('utf-8') to reset the runtime environment Encoding
Processing the encoding text is a routine. decode the source format first, and then encode the desired format.