The partition() method of bytearray class in Python

The partition method of bytearray class in Python splits the bytearray into three parts. The left part of the byte array, separator and the right part of the byte array. All the parts are returned as the elements of a tuple.

Bytearray Updated 14 Nov 2025 1 min read

Overview

  • The method partition() of bytearray class splits the bytearray into two based on the given separator.
  • The separator can consist of a single byte or more than one byte.
  • The partition() method returns the first part, separator and the second part as a tuple. Each part in the tuple including the separator is returned as a bytearray.

Example

python
# Example Python program that creates

            # partitions of a bytearray based on a given

            # byte-sequence

# Create a bytearray

            bytes2Partition = bytearray(b"Of shoes--and ships--and sealing-wax--")

# Specify the byte(s) on which to partition the bytearray

            partitionChar = b"--"

# Partition the byte array

            portions = bytes2Partition.partition(partitionChar)

            for portion in portions:

                print(portion)

Output

Output
bytearray(b'Of shoes')

            bytearray(b'--')

            bytearray(b'and ships--and sealing-wax--')