我有一些字节
。
b'\x01\x02\x03'
并且一个范围在0到255之间的int
。
5
现在我想把 int
附加到 bytes
中,就像这样:
b'\x01\x02\x03\x05'
怎么做?bytes
中没有append
方法。我甚至不知道如何将整数变成单个字节。
>>> bytes(5)
b'\x00\x00\x00\x00\x00'
我有一些字节
。
b'\x01\x02\x03'
并且一个范围在0到255之间的int
。
5
现在我想把 int
附加到 bytes
中,就像这样:
b'\x01\x02\x03\x05'
怎么做?bytes
中没有append
方法。我甚至不知道如何将整数变成单个字节。
>>> bytes(5)
b'\x00\x00\x00\x00\x00'
bytes
是不可变的。使用bytearray
。
xs = bytearray(b'\x01\x02\x03')
xs.append(5)
n
) 传递给 bytes()
将返回一个长度为 n
且包含空字节的字节串。所以这不是你想要的:>>> bytes([5]) #This will work only for range 0-256.
b'\x05'
>>> bytes(chr(5), 'ascii')
b'\x05'
正如@simonzack已经提到的那样,字节是不可变的,所以要更新(或者更确切地说是重新赋值)它的值,你需要使用+=
运算符。
>>> s = b'\x01\x02\x03'
>>> s += bytes([5]) #or s = s + bytes([5])
>>> s
b'\x01\x02\x03\x05'
>>> s = b'\x01\x02\x03'
>>> s += bytes(chr(5), 'ascii') ##or s = s + bytes(chr(5), 'ascii')
>>> s
b'\x01\x02\x03\x05'
bytes()
帮助文档:
>>> print(bytes.__doc__)
bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object
Construct an immutable array of bytes from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- any object implementing the buffer API.
- an integer
如果您需要一个可变对象,而且只关心0-256范围内的整数,那么可以选择可变的bytearray
。
bytes((5,))
来优化第一种方法,以及使用(5).to_bytes(1, "little")
来优化第二种方法。int.to_bytes()
可用于从任意大小的整数中按指定顺序获取更长的字节序列。 - Bachsau
bytearray
只能存储 0-256 范围内的整数。尽管在这种情况下,OP 只关心相同的范围。 :-) - Ashwini Chaudharybytearray
有.extend
方法,可以一次性添加更多的字节,例如xs.extend(b'\x11\x22\x33')
。该方法可在现有字节数组末尾添加指定字节序列。 - pepr