Python: Underlying data type---bytes
Because the Python string type is str , in memory, in Unicode, one character corresponds to a number of bytes. If you want to transfer on a network, or save to disk, you need to turn it str into bytes bytes .
Python bytes uses b a prefixed single or double quotation mark for data of type:
B1 = b'Alex'print(B1,type (B1) b'Alex' <class'bytes'>
要注意区分‘ABC‘和b‘ABC‘,前者是str,后者虽然内容显示得和前者一样,但bytes的每个字符都只占用一个字节。
The string and the bytes are converted to each other:
S1 = " alex " # str---> bytes encode encoding B1 = S1.encode ( Span style= "COLOR: #800000" >utf-8 " ) print (B1) # bytes---> str decode decoding s2 = b1.decode ( Span style= "COLOR: #800000" >utf-8 " ) print (S2) b " alex " alex
Specify the encoding transformation:
' Alex ' = S1.encode (' gbk'= B2.decode ('gbk' ) )print(b2)print(S3) b'Alex' Alex
When the Chinese conversion, different encoding can not directly convert the error as follows
' China ' = S4.encode (' utf-8'= B4.decode ('gbk' ) )print(S5)' GBK ' codec can ' t decode byte 0xad in position 2:illegal Multibyte sequence
S4 ='China'B4= S4.encode ('Utf-8')# utf-8 BytesPrint(B4) B6= B4.decode ('Utf-8') # Utf-8 UnicodePrint(B6) B7= B6.encode ('GBK') # GBK bytesPrint(B7) b'\XE4\XB8\XAD\XE5\X9B\XBD' #不同编码的bytes数据, not the same lengthChina b'\XD6\XD0\XB9\XFA'
Python: Underlying data type: bytes