Python has two types of strings: strobject and unicodeobject, both of which can store the byte encoding of characters, but they are different types, which is very important, it is also the reason why python has str object and unicode object strings that can both store character byte encoding, but they are different types. this is very important and is also why there is encode and decode.
The meaning of encode and decode in pyhton can be expressed
Encode
Unicode ---------------------------> str
Unicode <-------------------------- str
Decode
Several common methods:
Str_string.decode ('codec') is to convert str_string to unicode_string. codec is the encoding method of the source str_string.
Unicode_string.encode ('codec') is to convert unicode_string to str_string, and codec is the encoding method of the target str_string.
Str_string.decode ('from _ Codec'). encode ('to _ Codec') can be converted between str_strings of different encodings.
For example:
>>> T = 'Great Wall'
>>> T
'\ Xb3 \ xa4 \ xb3 \ xc7'
>>> T. decode ('gb2312'). encode ('utf-8 ')
'\ Xe9 \ x95 \ xbf \ xe5 \ x9f \ x8e'
Str_string.encode ('codec') first calls the system's default codec to convert str_string to unicode_string, and then converts it to the final str_string using the codec parameter of encode. equivalent to str_string.decode ('sys _ Codec '). encode ('codec ').
Unicode_string.decode ('codec') is basically meaningless. unicode only uses one unicode encoding type in python, UTF16 or UTF32 (determined when compiling python), and there is no need for encoding conversion.
Note: By default, codec is specified in the sitecustomize. py file under site-packages, for example
Import sys
Sys. setdefaultencoding ('utf-8 ')