python3 bytes和bytearray总结

本文详细介绍了Python中用于操作二进制数据的字节(bytes)和字节数组(bytearray)类型。解释了如何创建这些类型,包括使用函数、直接定义和类型转换。同时,对比了bytes与bytearray的区别,以及它们的常用方法,如查找、替换和十六进制转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The core built-in types for manipulating binary data are bytes and bytearray. They are supported by memoryview which uses the buffer protocol to access the memory of other binary objects without needing to make a copy.

用于操作二进制数据的核心内置类型是字节和字节数组。memoryview支持它们,它使用缓冲区协议访问其他二进制对象的内存,而不需要进行复制。

bytearray objects are a mutable counterpart to bytes objects.

bytearray对象是与bytes对象相对应的可变对象。

bytes定义

1.使用bytes函数创建bytes

  • bytes() 创建一个空的bytes
  • bytes(int) 创建一个int位的全位0的bytes
  • bytes(iterabl_of_ints) 可迭代数字组成的bytes(比如range)
  • bytes(string,encoding[,errors]) 等价于string.encode()
  • bytes(bytes of buffer) 创建一个bytes的copy

2.直接定义

比如:

​ b = b'abc'

​ b = b'\x61'

3.类型转换

  • string.encode()
  • int.tobytes()
  • bytes.from

bytes函数定义

>>> bytes()
b''
>>> bytes(3)
b'\x00\x00\x00'
>>> bytes(range(3))
b'\x00\x01\x02'
>>> b = bytes('中国', encoding='utf-8')
>>> b
b'\xe4\xb8\xad\xe5\x9b\xbd'
>>> bytes(b)
b'\xe4\xb8\xad\xe5\x9b\xbd'


直接创建:

>>> b = b'abc'
>>> b
b'abc'

类型转换:

>>> n = 97
>>> n.to_bytes(1,byteorder='big')
b'a'
>>> s = '中国'

>>> s.encode(encoding = 'utf-8')
b'\xe4\xb8\xad\xe5\x9b\xbd'


>>> bytes.fromhex('61')
b'a'

bytes的显示方式

Only ASCII characters are permitted in bytes literals (regardless of the declared source code encoding). Any binary values over 127 must be entered into bytes literals using the appropriate escape sequence.

只有ASCII中的字符串是可以直接在bytes类型中显示出来的,所有大于127的数值用转义字符表达。

比如,内存中的字节对象用十六进制表示为61,在python中显示的方式不是b'\x61' 而是b'a';而b'\xe4'显示方式就是b'\xe4';注意:仅仅是显示方式而已

另外,并不是所有的小于127的都可以被友好的显示出来,有些对象本身不可显示,就显示其十六进制表示。比如

b'\x00'

bytes的一般方法

bytes类似于string;在方法上,除了自己特有的方法外,跟str也类似。

比如:

>>> b'abc'.find(b'\x63')
2
>>> b'abc'.replace(b'\61',b'A')
b'abc'

bytearray定义

bytearray是可变的bytes数据类型,可以通过bytearray创建和定义

一:bytearray()定义

  • bytearray() 创建一个空的bytearray
  • bytearray(int) 创建一个int位的全位0的bytearray
  • bytearray(iterabl_of_ints) 可迭代数字组成的bytearray(比如range)
  • bytearray(string,encoding[,errors]) 将一个字符串编码为bytearray
  • bytearray(bytes of buffer) 创建一个bytearray

二: bytearray的方法定义

  • bytearray.fromhex()

bytearray的一般方法

bytearray具备bytes的操作方法,像字符串一样操作;

另外bytearray还具备像list一样的操作方法,比如pop,append等

bytes 和 bytearray的方法

十六进制和字节类型的相互转换

  • bytes.fromhex()
  • bytearray.fromhex()
  • bytes.hex()
  • bytesarray.hex()
>>> b = bytes('hell',encoding='utf-8')
>>> ba = bytearray('hell',encoding='utf-8')
>>> b
b'hell'
>>> ba
bytearray(b'hell')
>>> b.hex()
'68656c6c'
>>> ba.hex()
'68656c6c'

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值