The representation of a string inside Python is a Unicode encoding.
As a result, in encoding conversions, Unicode is usually used as an intermediate encoding, in which other encoded strings are decoded (decode) into Unicode, and then from Unicode encoding (encode) to another encoding.
The role of decode is to convert other encoded strings into Unicode encoding, such as String1.decode (' Utf-8 '), which means converting the UTF-8 encoded string string1 to Unicode encoding.
The role of encode is to convert Unicode encoding to other encoded strings, such as String2.encode (' Utf-8 '), which means converting a Unicode-encoded string string2 to a utf-8 encoding.
If a string is already Unicode, then the decoding is an error, so it is usually judged by whether the encoding is Unicode:
Isinstance (String3, Unicode) #用来判断string3是否为unicode编码
String3 in the form of non-Unicode encoding can also be used to encode the error.
#获得系统的默认编码
#!/usr/bin/env python
#coding =utf-8
import sys
print sys.getdefaultencoding ()
#万能方法
#!/usr/bin/env python
#coding =utf-8
string4= "Hello"
if Isinstance (String4, Unicode):
print S.encode (' gb2312 ')
else:
print s.decode (' utf-8 '). Encode (' gb2312 ')