标签(空格分隔): python-数据结构
bytes
bytearry
有序序列
,字符可以使用编码来理解bytes
是字节组成的有序的
,不可变序列
bytearray
是字节组成的有序的
,可变序列
encode
返回字节序列 bytes
encode(encoding="utf-8", error="strict") --> bytes
decode
返回字符串
bytes.decode(encoding="utf-8", error="strict") --> str
bytearray.decode(encoding="utf-8", error="strict") --> str
bytes()
空 bytesbytes(int)
指定字节的bytes,被 0 填充bytes(iterable_of_in) --> bytes
[0, 255] 的int组成的可迭代对象bytes(string, encoding[, errors]) -> bytes
等价于 string.encode()
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
从一个字节序列或者buffer复制除一个新的不可变的bytes对象[x] bytes 操作
和str类型类似,都是不可变类型,所以方法很多都一样,只不过bytes的方法,输入是bytes,输出也是 bytes
>>> b"abc".find(b"b")
... 1
>>> b"abcdef".replace(b"f", b"123")
... b'abcde123'
bytes.fromhex(string) ---> bytes
>>> bytes.fromhex("6162 6a 6b")
... b'abjk'
>>> bytes.fromhex("6162 6a 6b").decode()
... 'abjk'
>>> "中".encode()
... b'\xe4\xb8\xad'
>>> bytes.fromhex("e4b8ad")
... b'\xe4\xb8\xad'
>>> bytes.fromhex("e4b8ad").decode()
... '中'
>>> "{:X}{:X}{:X}".format(*"中".encode())
... 'E4B8AD'
>>> bytes.fromhex("{:X}{:X}{:X}".format(*"中".encode()))
... b'\xe4\xb8\xad'
>>> bytes.fromhex("{:X}{:X}{:X}".format(*"中".encode())).decode()
... '中'
[x] hex() ---> int
返回 16 进制表示的字符串
>>> "abc".encode().hex()
... '616263'
>>> "中".encode().hex()
... 'e4b8ad'
>>> bytes.fromhex("中".encode().hex())
... b'\xe4\xb8\xad'
>>> bytes.fromhex("中".encode().hex()).decode()
... '中'
bytearray()
空bytearray
bytearray(int)
指定字节的bytearray
,被 0 填充bytearray(iterable_of_in) --> bytearray
[0, 255] 的int组成的可迭代对象bytearray(string, encoding[, errors]) -> bytearray
近似于 string.encode()
,不过返回可变的对象bytearray(bytes_or_buffer) -> immutable copy of bytes_or_buffer
从一个字节序列或者buffer复制除一个新的不可变的bytearray对象注意: b 前缀定义的类型是 bytes类型的
[x] bytearray 操作
和 bytes 类型的方法相同
>>> bytearray(b"abc").find(b"b")
... 1
>>> bytearray(b"abcdef").replace(b"f", b"123")
... bytearray(b'abcde123')
bytearray.fromhex(string) ---> bytearray
>>> bytearray.fromhex("6162 6a 6b")
... bytearray(b'abjk')
>>> bytearray.fromhex("6162 6a 6b").decode()
... 'abjk'
>>> "中".encode()
... b'\xe4\xb8\xad'
>>> bytearray.fromhex("e4b8ad")
... bytearray(b'\xe4\xb8\xad')
>>> bytearray.fromhex("e4b8ad").decode()
... '中'
>>> "{:X}{:X}{:X}".format(*"中".encode())
... 'E4B8AD'
>>> bytearray.fromhex("{:X}{:X}{:X}".format(*"中".encode()))
... bytearray(b'\xe4\xb8\xad')
>>> bytearray.fromhex("{:X}{:X}{:X}".format(*"中".encode())).decode()
... '中'
[x] hex() ---> int
返回 16 进制表示的字符串
[x] 索引 ---> int
bytearray(b"abcdef")[2]
返回改字节对应的数,int 类型
>>> bytearray(b"abcdef")[2]
... 99
append(int)
尾部追加一个元素insert(index,int)
在指定索引位置上插入元素extend(iterable_int)
将一个可迭代的整数集合追加到当前的 bytearry
pop(index=-1)
从指定索引上移除元素,默认从尾部移除remove(value)
找到一个value
移除,找不到 则 ValueError
异常上述方法中若要使用int类型,值必须在 [0, 255] 之间
clear()
清空 bytearry
reverse()
翻转 bytearry
,就地修改原文:https://www.cnblogs.com/jingru-QAQ/p/11405626.html