前言
最近在整一些跟二进制有关的,网上没有,遂写此文
*本文基于python3
bytes
不可变类型,主要可以由str.encode
和bytes(...)
创建。
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