bytes和bytearray
python - Bytes和Bytearray
标签(空格分隔): python-数据结构
bytes、bytearray
-
-
- 不可变字节序列
-
- 字节数组
- 可变
-
-
- 字符串是字符组成的
有序序列,字符可以使用编码来理解 bytes是字节组成的有序的,不可变序列bytearray是字节组成的有序的,可变序列
- 字符串是字符组成的
-
- 字符串按照不同的字符集编码
encode返回字节序列 bytesencode(encoding="utf-8", error="strict") --> bytes
- 字节序列按照不同的字符集解码
decode返回字符串bytes.decode(encoding="utf-8", error="strict") --> strbytearray.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对象- 使用 b前缀定义
- 只允许 基本的 ASCII 使用字符形式 b"abc9"
- 使用十六进制表示 b"\x41\x61"
-
和str类型类似,都是不可变类型,所以方法很多都一样,只不过bytes的方法,输入是bytes,输出也是 bytes
>>> b"abc".find(b"b") ... 1 >>> b"abcdef".replace(b"f", b"123") ... b'abcde123'-
- string 必须是 2 个字符的 16进制的形式, "6162 6a 6b",空格将被忽略
>>> 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() ... '中' -
返回 16 进制表示的字符串
>>> "abc".encode().hex() ... '616263' >>> "中".encode().hex() ... 'e4b8ad' >>> bytes.fromhex("中".encode().hex()) ... b'\xe4\xb8\xad' >>> bytes.fromhex("中".encode().hex()).decode() ... '中'
-
-
bytearray()空bytearraybytearray(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类型的
-
和 bytes 类型的方法相同
>>> bytearray(b"abc").find(b"b") ... 1 >>> bytearray(b"abcdef").replace(b"f", b"123") ... bytearray(b'abcde123')-
- string 必须是 2 个字符的 16进制的形式, "6162 6a 6b",空格将被忽略
>>> 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() ... '中' -
返回 16 进制表示的字符串
-
>>> bytearray(b"abcdef")[2] ... 99
上述方法中若要使用int类型,值必须在 [0, 255] 之间
-

浙公网安备 33010602011771号