bytes.rstrip() returns a new bytes object with bytes removed from the right end only. With no argument it removes ASCII whitespace; with chars it removes any byte that appears in that set.
It is the everyday way to drop \r\n from lines read in binary mode and to trim the zero bytes that pad fixed-size name fields in binary file formats.
bytes.rstrip() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.rstrip(...). No import is needed, and bytearray objects have the same method.
Syntax
Strip trailing whitespace, or a set of bytes you choose.
python
result = data.rstrip()
result = data.rstrip(chars)
Call
What it does
b"line\r\n".rstrip()
Returns b'line'.
b"name\x00\x00".rstrip(b"\x00")
Returns b'name'.
b" hi ".rstrip()
Returns b' hi': leading spaces stay.
rstrip(b"\r\n") removes any mix of CR and LF bytes at the end, not only one CRLF pair.
Method signatures
python
bytes.rstrip(chars=None, /)
# chars: bytes-like set of byte values; None means ASCII whitespace
Parameters
Parameter
Description
chars
Optional. The set of byte values to remove from the right. Default None removes ASCII whitespace.
Return Value
Return Value
Description
bytes
A copy without the trailing bytes that belong to the set.
Python Examples
Example 1 — Drop Line Endings, Keep Other Spaces
Compare stripping only CR and LF with stripping all whitespace on lines read in binary mode.
python
lines = [b"alpha\r\n", b"beta\n", b"gamma \n"]
print([line.rstrip(b"\r\n") for line in lines])
print([line.rstrip() for line in lines])