我如何 truncate/restrict/limit Python 中 bytearray 的长度?

How do I truncate/restrict/limit the length of bytearray in Python?

假设我有一个长度为 50(50 字节)的字节数组,但我只需要字节数组的前 25 个字节。我该怎么做?

例如:

c = bytearray(b'1703020030f19322e5cc9b9e56cb71d2ebcd888582913f7f13')

d= bytearray(b'\x17\x03\x03\x000\xd9O\x8a\x08L\t\x05:\xf6\xa0\x0b\xc0\xb6\xcc\xf5\x1a\xc5S\xf9\x98\xf4\gTf\xcco\xc7\x10\x16\x1f\xf5\xcd`\x9f=K.\x8aj\x0b]\x9eW\xd0\x04\x17\xcd')

len(c) = 50len(d) = 53.

如何只提取它的前 50 个字节并丢弃其余字节?

提前致谢!

bytearray 是一个序列,因此您可以将其切片:

d = d[:50]

或者,如果性能很关键,为了避免不必要的复制,字节数组通常会比您的限制短:

if len(d) > 50:
    d = d[:50]