bytes.strip()
The argument is a SET of bytes to remove, not a prefix to match. That one misunderstanding accounts for nearly every strip bug ever written.
Demo
The second case is the one to study. Stripping "ab" from "abcba" gives "c" — it removed a, then b from the front, and a, then b from the back, because the argument is a SET of bytes to keep removing while they match. It is not a prefix or suffix. The middle case shows the other half of the rule: only the ends are considered, so an x between other bytes survives.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| chars | bytes | no (None) | A SET of byte values to strip from both ends. Omitted or None strips ASCII whitespace: space, tab, newline, carriage return, vertical tab and form feed. |
Return value
bytes — A new bytes object with leading and trailing bytes removed. Only the ends are touched; the middle is untouched.
Common patterns
clean = raw_line.strip()
value = field.strip(b'\x00')
data.rstrip(b'\n')
Examples
Pitfalls
b'testfile.txt'.strip(b'.txt')
b'testfile.txt'.removesuffix(b'.txt')
b'xaxbx'.strip(b'x')
b'xaxbx'.replace(b'x', b'')
b'xxa'.strip('x')
b'xxa'.strip(b'x')
data.strip() data
data = data.strip()
When to use
- Trimming whitespace or line endings from binary-mode input
- Removing padding bytes from fixed-width fields
- Cleaning the ends of a token before parsing it
- Removing a known prefix or suffix → removeprefix and removesuffix
- Removing a byte everywhere → replace
- The data is text → decode first and use str.strip
Notes
FAQ
Because it strips the SET of bytes dot, t, x — not the suffix. Any of those at either end is removed, repeatedly, until something else appears. removesuffix is what you actually wanted.
b'testfile.txt'.removesuffix(b'.txt')