Work - Error summary

### Python coding problems

### 一、解决UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range

Python string representation is internally unicode encoding, therefore, when doing transcoding, usually required as an intermediate to unicode coding, i.e. decoding other encoded first string (decode) into unicode, and from unicode encoding (encode) to another encoding. 
       
       Decode role is to convert the string into other coding unicode encoding, such as str1.decode ( ' gb2312 ' ), represents the encoded string str1 gb2312 converted into unicode encoding. 

       Encode role is to convert unicode string encoded into other coding, such as str2.encode ( ' gb2312 ' ), it indicates to convert the unicode string encoded into str2 gb2312 coding. 

       Thus, when transcoding must first thoroughly understand what the string str encoded, then decode to unicode, and then encode into other coding 

       code string default encoding is consistent with the code file encoding itself. 

       python during installation, the default encoding is ascii, when non-ascii coding occurs in a program, python treatment often report such a mistake UnicodeDecodeError: ' ascii ' CODEC CAN 't decode byte 0x ?? in position 1: ordinal not in range (128), python can not handle non-ascii-encoded, this time need to set the default encoding of python, generally set the utf8 encoding format.
the reason
# Python2 

in the following three files 
 Import SYS 
 reload (SYS) 
 sys.setdefaultencoding ( ' UTF8 ' ) 


# to python3

 

 

Guess you like

Origin www.cnblogs.com/sunxiuwen/p/11791469.html