In the console under Windows, this should be the logic:
1, if it is a Unicode string, the first conversion based on the console encoding
2, after the output
So under Windows console, suppose str = u ' Chinese ',
1, direct print str can be correctly output
2. Print Str.encode (' GBK ') or print str.encode (' gb2312 ') is output correctly
3, Print Str.encode (' utf-8 ') is output garbled
In sublime text under Windows system, suppose str = u ' Chinese ',
1, if the direct print str, will prompt
' ASCII ' codec can ' t encode characters in position 0-1: Ordinal not in range (128)
This is because it attempts to encode a Unicode string using the system default encoding (which is ASCII by default in Windows), and it must be a failure to encounter Chinese
2, if Print str.encode (' utf-8 ') can be correctly output in sublime text
3, if Pirnt str.encode (' GBK ') or print str.encode (' gb2312 '), will prompt
[Decode error-output not Utf-8]
Maybe it's because sublime text only accepts utf-8 output.
Summarizing the above process, the Sublime text process should be
1. Determine if the string is Unicode
2, if it is, first use the system default code for encode
3. Determine if the byte string is utf-8 encoded, and if so, the output
To solve the problem of sublime text under Windows, there are two ways to do this:
1. Add the following code to the program's head
Import'utf-8'if sys.getdefaultencoding ()! = Default_ Encoding: Reload (SYS) sys.setdefaultencoding (default_encoding)
There is said to be inserted into the sublime_plugin.py, but the test, no
2, add pythonioencoding in the system environment variable (case does not matter), the value is Utf-8
This way, when you want to output Chinese, the direct print Str,str is a Unicode string, which is the correct result either in sublime text or console!
Note:
Chardet can be used to detect the file encoding, as well as the codecs module to do some coding related work, the following article can be used as a reference to file encoding related issues
Python character encoding problem, chardet,codecs
Reference article:
python-Advanced-Coding Processing Summary
Some problems of sublime and Python coding in Chinese