TOC

Python bytes 类型

  1. bytes 按索引取值得到的是整数。

    b'abc'[0]
    97
    
  2. strbytes 只需要编码一下就行了。反过来就是解码一下。

    s = '你好'
    b = bytes(s, 'utf-8')
    # b'\xe4\xbd\xa0\xe5\xa5\xbd'
    assert b.decode('utf-8') == s
    
    bytes('hello')
    TypeError: string argument without an encoding
    
    bytes('hello', 'ascii')
    b'hello'
    
    'hello'.encode()
    b'hello'
    
    bytes('hello', 'utf-16')
    b'\xff\xfeh\x00e\x00l\x00l\x00o\x00'
    
    bytes('hello', 'utf-32')
    b'\xff\xfe\x00\x00h\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00'
    
  3. bytesint 列表的转换。

    list(b'abc')
    [97, 98, 99]
    
    bytes([97, 98, 99])
    b'abc'
    
    bytes([256])
    ValueError: bytes must be in range(0, 256)
    
    # 大端序
    (2008).to_bytes(length=4, byteorder='big', signed=False)
    b'\x00\x00\x07\xd8'
    # 小端序
    (2008).to_bytes(length=4, byteorder='little', signed=False)
    b'\xd8\x07\x00\x00'
    struct.pack('<I', 2008)
    b'\xd8\x07\x00\x00'
    
    int.from_bytes(b'\x00\x00\x07\xd8', 'big')
    2008
    int.from_bytes(b'\xd8\x07\x00\x00', 'little')
    2008
    
    int.from_bytes(b'abc', 'little')
    6513249
    int.from_bytes(b'cba', 'big')
    6513249
    

    PS:2020/11/02, 字节顺序(大端序、小端序)

  4. Python2 字符串

    # python2
    print(repr('你好'))
    '\xc4\xe3\xba\xc3'
    print('\xc4\xe3\xba\xc3')
    你好
    
    # python3
    print('\xc4\xe3\xba\xc3')
    'ÄãºÃ'
    print('\xc4\xe3\xba\xc3'.encode('latin-1'))
    b'\xc4\xe3\xba\xc3'
    print('\xc4\xe3\xba\xc3'.encode('latin-1').decode('gbk'))
    '你好'