如何在Python 3中向字节中添加内容

69

我有一些字节

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'
2个回答

82

bytes是不可变的。使用bytearray

xs = bytearray(b'\x01\x02\x03')
xs.append(5)

请注意,bytearray 只能存储 0-256 范围内的整数。尽管在这种情况下,OP 只关心相同的范围。 :-) - Ashwini Chaudhary
40
bytearray.extend 方法,可以一次性添加更多的字节,例如 xs.extend(b'\x11\x22\x33')。该方法可在现有字节数组末尾添加指定字节序列。 - pepr
17
@Ashwini,(0-255) 的意思是指一个数字范围在 0 到 255 之间。 - Larry
15
还有什么其他的可以适应一个字节的东西吗? - Sherlock70

27
首先,将一个整数(比如说 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
3
对于你想让我翻译的内容:"FWIW, a byte is 0..255, not 0..256",我的翻译如下:"FWIW,一个字节的范围是0到255,而不是0到256。" - Russ Schultz
+1 是因为提到了 += 运算符,我不知道为什么 .append() 只适用于整型,却不能传入 bytes 或者另一个 bytearray 对象,真是让人恼火。 - mgrandi
@mgrandi 使用 .extend() 而不是 += - toppk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接