加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

bytes和bytearray总结

发布时间:2020-12-14 03:50:26 所属栏目:大数据 来源:网络整理
导读: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. bytearray objects ar

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.

bytearray objects are a mutable counterpart to bytes objects.

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‘x00x00x00‘
>>> bytes(range(3))
b‘x00x01x02‘
>>> b = bytes(‘中国‘,encoding=‘utf-8‘)
>>> b
b‘xe4xb8xadxe5x9bxbd‘
>>> bytes(b)
b‘xe4xb8xadxe5x9bxbd‘

直接创建:

>>> b = b‘abc‘
>>> b
b‘abc‘

类型转换:

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

>>> s.encode(encoding = ‘utf-8‘)
b‘xe4xb8xadxe5x9bxbd‘


>>> 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,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‘

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读