如何在python 3中附加到字节

fel*_*ade 24 python python-3.x

我有一些bytes.

b'\x01\x02\x03'
Run Code Online (Sandbox Code Playgroud)

并且int范围为0..255.

5
Run Code Online (Sandbox Code Playgroud)

现在我想附加intbytes这样的:

b'\x01\x02\x03\x05'
Run Code Online (Sandbox Code Playgroud)

怎么做?没有append方法bytes.我甚至不知道如何使整数成为单个字节.

>>> bytes(5)
b'\x00\x00\x00\x00\x00'
Run Code Online (Sandbox Code Playgroud)

sim*_*ack 30

bytes是不可改变的.使用bytearray.

xs = bytearray(b'\x01\x02\x03')
xs.append(5)
Run Code Online (Sandbox Code Playgroud)

  • @AshwiniChaudhary 还有什么可以容纳在一个字节中? (8认同)
  • @Ashwini,(0-255) (7认同)
  • `bytearray`有`.extend`方法一次添加更多字节,如`xs.extend(b'\ x11\x22\x33')`. (5认同)

Ash*_*ary 11

首先传递一个整数(比如说n),bytes()只返回一个n长度为null 的字节字符串.所以,这不是你想要的:

要么你能做到:

>>> bytes([5]) #This will work only for range 0-256.
b'\x05'
Run Code Online (Sandbox Code Playgroud)

要么:

>>> bytes(chr(5), 'ascii')
b'\x05'
Run Code Online (Sandbox Code Playgroud)

由于@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'
Run Code Online (Sandbox Code Playgroud)

帮助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
Run Code Online (Sandbox Code Playgroud)

或者bytearray如果你需要一个可变对象,你可以选择mutable,而你只关心0-256范围内的整数.

  • FWIW,一个字节是0..255,而不是0..256 (3认同)