What is the bytes removeprefix() method in Python?

Overview

The bytes.removeprefix() method returns the bytes[len(prefix):] if the binary data starts with the prefix string. Otherwise, the original binary data is returned.

New in Python 3.9!

Syntax


bytes.removeprefix(prefix, /)

Parameter value

It takes the following argument value:

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

Return value

The bytes.removeprefix() method returns a bytes object, bytes[len(prefix):].

Example

In the code snippets below, we are going to discuss whether the given object contains 'Test' bytes or not.

# bytes type object
message = b'Test your coding skills with Educative!'
# invoking removeprefix() to remove Test prefix
print(message.removeprefix(b'Test'))

Explanation

  • Line 2: We create a bytes type object that contains the 'Test your coding skills with Educative!' string as bytes.
  • Line 4: We invoke the removeprefix() method to remove the prefix 'Test' bytes from the bytes object we created above. This returns a bytes object that contains b' your coding skills with Educative!'.
# Created a bytes type object
message= b'I love to Code!'
# invoking removeprefix() to remove Code prefix
print(message.removeprefix(b'Code'))

Explanation

  • Line 2: We create a bytes type object that contains the 'I love to Code!' string as bytes.
  • Line 4: We invoke the removeprefix() method to remove the prefix 'Code' bytes from the bytes object we created above. If the binary data does not contain the given prefix, then the method returns the bytes object as it is.

Free Resources