Search code examples
pythonarraysbytestring-length

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


Let's say I have a bytearray of length 50 (50 bytes) but I want only the first 25 bytes from the bytearray. How do I do that?

For example:

c = bytearray(b'1703020030f19322e5cc9b9e56cb71d2ebcd888582913f7f13')

or

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) = 50 and len(d) = 53.

How do I just extract the first 50 bytes of it and discard the rest?

Thanks in advance!


Solution

  • A bytearray is a sequence, so you can just slice it:

    d = d[:50]
    

    Or, to avoid unnecessary copies if performance is critical and the bytearray will usually be shorter than your limit:

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