What is the bytes removesuffix() method in Python?

Overview

The bytes instance stores an immutable sequence of bytes values. The bytes.removesuffix() method returns the bytes[:-len(suffix)] if the binary data ends with the suffix string and is not empty. Otherwise, the original binary data is returned.

bytes[:-len(suffix)] means it will return bytes data from start0th index until lengthTotal length of string, excluding the length of the suffix string from the end of the called object.

New in Python 3.9

Syntax


bytes.removesuffix(suffix, /)

Parameter value

It takes the following argument value:

  • suffix: This shows the defined suffix that needs to be removed.

Return value

The removesuffix() method returns a bytes type object in the form bytes[:-len(suffix, /).

Example

In this example, we are going to discuss the removesuffix() function. Here, we have two cases, either a string has a suffix or it does not.

# Program: When calle string has suffix string
# creating a bytes instance
message = b'Hello, Welcome to work'
# invoking removesuffix() to remove work suffix
print(message.removesuffix(b'work'))

Explanation

  • Line 3: We create a bytes type object from the 'Hello, Welcome to work' string.
  • Line 5: We invoke the removesuffix() method to remove the work suffix from the bytes object we created above. This returns a bytes type object bytes[:-len(suffix, /). It outputs b'Hello, Welcome to ' as a sequence of bytes.

Example

# Creating a bytes type object
title= b'Test your coding skills at Educative!'
# checking for Test suffix
print(title.removesuffix(b'Test'))

Explanation

  • Line 2: We create a bytes type object from the 'Test your coding skills at Educative!' string.
  • Line 4: We invoke the removesuffix() method to remove the 'Test' suffix. However, the given binary data does not contain 'Test' as a suffix.

Free Resources