The representation of a string inside Python is a Unicode encoding (8-bit string), so it is often necessary to use Unicode as an intermediate encoding for encoding conversions, that is, decoding the other encoded strings (decode) into Unicode first. From Unicode encoding (encode) to another encoding.
The role of Decode is to convert other encoded strings into Unicode encodings, such as Str1.decode (' gb2312 '), to convert gb2312 encoded string str1 into Unicode encoding.
The role of encode is to convert Unicode encoding into other encoded strings, such as Str2.encode (' gb2312 '), to convert Unicode encoded string str2 to gb2312 encoding.
Therefore, the transcoding must first understand, the string str is what encoding, and then decode into Unicode, and then encode into other encodings.
such as: s= ' Chinese '
If it is in a UTF8 file, the string is UTF8 encoded, and if it is in a gb2312 file, it is encoded as gb2312. In this case, to encode the conversion, you need to first convert it to Unicode encoding using the Decode method, and then use the Encode method to convert it to another encoding. Typically, you create a code file by using the system default encoding when you do not specify a specific encoding method.
If the string is defined like this: S=u ' Chinese '
The encoding of the string is specified as Unicode, which is the internal encoding of Python, regardless of the encoding of the code file itself. Therefore, for this case to do the encoding conversion, only need to directly use the Encode method to convert it to the specified encoding.
Get the current Environment default encoding
Import SYS Print sys.getdefaultencoding () ASCII
Modify the current encoding
>>> isinstance (s,unicode) False>>> sys.setdefaultencoding ("gbk" )>>> Unicode (s) u'\u4e2d\u6587'>>> S.decode () u'\u4e2d\u6587'
Python Decode and encode