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

The replace() method of bytearray class

Method signature:

replace(old, new, count=-1)

Parameters:

old - The subsequences that is to be found and replaced.

new -  The subsequence with which the found subsequences to be replaced.

count - Number of replacements to be performed.

Return value:

The new bytearray object with the find and replacements in-place.

Overview:

 

The replace() function of bytearray class in Python

  • The replace() method of bytearray does a find and replace for a given bytearray obejct and returns the new bytearray. The “find” subsequences are replaced with the “replace” subsequences in the new bytearray.
  • A count can be specified to do find and replace only the “count” number of times. Further occurrences of the "find" subsequences are retained without replacement.

Example 1 - Perform find and replace on a Python bytearray:

# Example Python program that uses the bytearray method 
# replace() to get a new bytearray with specified subsequences 
# replaced with the new subsequences

# Create a byte sequence
byteSequence = bytearray(b"I wish I could manage to be glad")

find = b"I"
replace = b"you"

# Find and replace
newSequence = byteSequence.replace(find, replace)

# Print the new byte sequence
print(newSequence)

Output:

bytearray(b'you wish you could manage to be glad')

Example 2 - Replace old with new on a bytearray for count number of times:

# Example Python program that does 
# the "find and replace" operation 
# for the specified "count" number of 
# times on a bytearray

# Create a byte array
byteSeq = "A pleasant walk, a pleasant talk"

old = "pleasant"
new = "nice"
count = 1

# Replace old with new byte sequence 
newbyteSeq =  byteSeq.replace(old, new, count)
print(newbyteSeq)

Output:

A nice walk, a pleasant talk

 


Copyright 2025 © pythontic.com