The endswith() method of bytearray class in Python

Overview:

  • On a given bytearray object, the method endswith() checks for a specific suffix.
  • If the bytearray ends with the specified subsequence, then the method returns True. The method returns False otherwise.
  • The endswith() method can be specified of a start index and end index between which it can look for the suffix.

Example:

# Example Python program that finds whether a 
# bytearray ends with a specified subsequence

# Main sequence
sequence = b"I took the one less traveled by"

# Find whether the main sequence ends with the 
# given sub-sequence
subsequence = b"by"
endsWithBy  = sequence.endswith(subsequence)
print("The main sequence ends with {}:".format(subsequence))
print(endsWithBy)

Output:

The main sequence ends with b'by':

True

Example:

# Example Python program that finds whether a 
# bytearray has a suffix within the given start index
# and end index positions

byteSeq = b"So long lives this, and this gives life to thee."
subSeq  = b"this"

startPos = 0
endPos   = 18

# Find the suffix is present in the sequence as specified 
# by the start and end positions
hasSuffix = byteSeq.endswith(subSeq, startPos, endPos)
print("The suffix {} is present:".format(subSeq))
print(hasSuffix)

Output:

The suffix b'this' is present:

True

 


Copyright 2025 © pythontic.com