Python: Underlying data type: bytes

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.