【问题标题】:python3: bytes vs bytearray, and converting to and from stringspython3:字节与字节数组,并转换为字符串和从字符串转换
【发布时间】:2020-11-04 06:33:51
【问题描述】:

我想了解 python3 的 bytesbytearray 类。我看过关于它们的文档,但没有全面描述它们的区别以及它们如何与string 对象交互。

【问题讨论】:

    标签: python-3.x utf-8 utf


    【解决方案1】:

    bytes 和 bytearrays 类似...

    python3 的 bytesbytearray 类都保存字节数组,其中每个字节可以取 0 到 255 之间的值。主要区别在于 bytes 对象是不可变的 ,这意味着一旦创建,您就无法修改其元素。相比之下,bytearray 对象允许您修改其元素。

    bytesbytearay 都提供了对字符串进行编码和解码的函数。

    bytes 和编码字符串

    可以通过几种不同的方式构造字节对象:

    >>> bytes(5)
    b'\x00\x00\x00\x00\x00'
    
    >>> bytes([97, 98, 99])
    b'abc'
    
    >>> b'abc'
    b'abc'
    
    >>> bytes('abc')
    TypeError: string argument without an encoding
    
    >>> bytes('abc', 'utf-8')
    b'abc'
    
    >>> 'abc'.encode('utf-8')
    b'abc'
    
    >>> 'abc'.encode('utf-16')
    b'\xff\xfea\x00b\x00c\x00'
    
    >>> 'abc'.encode('utf-16-le')
    b'a\x00b\x00c\x00'
    

    注意最后两者的区别:'utf-16' 指定一个通用的 utf-16 编码,因此其编码形式包括一个两字节的“字节顺序标记”前导码 的[0xff, 0xfe]。当指定 'utf-16-le' 的显式排序时,如 后一个示例,编码形式省略了字节顺序标记。

    因为字节对象是不可变的,试图改变它的元素之一 导致错误:

    >>> a = bytes('abc', 'utf-8')
    >>> a
    b'abc'
    >>> a[1] = 102
    TypeError: 'bytes' object does not support item assignment
    

    字节数组和编码字符串

    bytes 一样,可以通过多种方式构造字节数组:

    >>> bytearray(5)
    bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')
    
    >>>bytearray([1, 2, 3])
    bytearray(b'\x01\x02\x03')
    
    >>> bytearray('abc')
    TypeError: string argument without an encoding
    
    >>> bytearray('abc', 'utf-8')
    bytearray(b'abc')
    
    >>> bytearray('abc', 'utf-16')
    bytearray(b'\xff\xfea\x00b\x00c\x00')
    
    >>> bytearray('abc', 'utf-16-le')
    bytearray(b'a\x00b\x00c\x00')
    

    因为字节数组是可变的,你可以修改它的元素:

    >>> a = bytearray('abc', 'utf-8')
    >>> a
    bytearray(b'abc')
    >>> a[1]=114
    >>> a
    bytearray(b'arc')
    

    附加字节和字节数组

    bytesbytearray 对象可以用 + 运算符连接:

    >>> a = bytes(3)
    >>> a
    b'\x00\x00\x00'
    
    >>> b = bytearray(4)
    >>> b
    bytearray(b'\x00\x00\x00\x00')
    
    >>> a+b
    b'\x00\x00\x00\x00\x00\x00\x00'
    
    >>> b+a
    bytearray(b'\x00\x00\x00\x00\x00\x00\x00')
    

    请注意,串联结果采用第一个参数的类型,因此a+b 产生一个bytes 对象,b+a 产生一个bytearray

    将字节和字节数组对象转换为字符串

    bytes 和 bytearray 对象可以使用decode 函数转换为字符串。该函数假定您提供与编码类型相同的解码类型。例如:

    >>> a = bytes('abc', 'utf-8')
    >>> a
    b'abc'
    >>> a.decode('utf-8')
    'abc'
    
    >>> b = bytearray('abc', 'utf-16-le')
    >>> b
    bytearray(b'a\x00b\x00c\x00')
    >>> b.decode('utf-16-le')
    'abc'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多