[二进制]Python中的bytes和bytearray

前言

最近在整一些跟二进制有关的,网上没有,遂写此文
*本文基于python3

bytes

不可变类型,主要可以由str.encodebytes(...)创建。

string = "hello"
b = string.encode()#UTF-8
print(repr(b))#b'hello'
print(b[0])#72

这个比较类似str,毕竟本身就可以由str转换来嘛

bytearray

可变,主要用bytearray(...)创建

string = "hello"
b = string.encode()
ba = bytearray(b)
print(repr(ba))#bytearray(x,x,x,x,x)

个人觉得类似list

对比一下

string,即非二进制

string = "hello"
print(string[0])

for s in string:
    print(s)

l = list(string)
print(l)

new = chr(72)
print(new)

l[1] = "h"
string[1] = "h"#ERROR!

二进制:

string = "hello"
b = string.encode()
print(b[0])

for bit in b:
    print(bit)

ba = list(b)
print(ba)

new = bytes(72)
print(new)

ba[1] = 72
b[1] = 72#ERROR!

运行结果

string:

h
h
e
l
l
o
['h', 'e', 'l', 'l', 'o']
H
Traceback (most recent call last):
  File "C:\Users\Xu\Desktop\test.py", line 14, in <module>
    string[1] = "h"#ERROR!
TypeError: 'str' object does not support item assignment

byte:

104
104
101
108
108
111
[104, 101, 108, 108, 111]
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
Traceback (most recent call last):
  File "C:\Users\Xu\Desktop\test.py", line 15, in <module>
    b[1] = 72#ERROR!
TypeError: 'bytes' object does not support item assignment

总结

个人认为,bytes类似str和list的结合体,而bytearray类似list

本文发于CSDN于2022/1/5 22:33

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值