Free cookie consent management tool by TermsFeed The partition() method of bytearray class in Python | Pythontic.com

The partition() method of bytearray class in Python

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:

# 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:

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

 


Copyright 2025 © pythontic.com