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
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 instancemessage = b'Hello, Welcome to work'# invoking removesuffix() to remove work suffixprint(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 objectbytes[:-len(suffix, /). It outputsb'Hello, Welcome to 'as a sequence of bytes.
Example
# Creating a bytes type objecttitle= b'Test your coding skills at Educative!'# checking for Test suffixprint(title.removesuffix(b'Test'))
Explanation
- Line 2: We create a
bytestype 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.