strip() removes unwanted characters from both ends of a string. With no argument it removes whitespace: spaces, tabs, and newlines. Characters in the middle are never touched, so " a b ".strip() is "a b".
You can pass a string of characters to remove instead. That argument is a set of characters, not a prefix or a suffix: strip("abc") removes any mix of a, b, and c from either end, for as long as the text keeps starting or ending with one of them. A string is never edited in place, so the method returns a new string.
text.strip() is a method of the built-in str type: call it on a string with dot notation. No import is needed, and it never changes the original string.
Syntax
Call it with no argument to trim whitespace, or pass the characters to remove.
python
clean = text.strip()
clean = text.strip(chars)
Call
What it does
" hello ".strip()
Returns 'hello'. Spaces on both sides are removed.
"xxhixx".strip("x")
Returns 'hi'. Every x at either end is removed.
"www.site.com".strip("w.moc")
Returns 'site'. The argument is a set of characters, so w, ., m, o, and c are all removed from the ends.
A set of two characters. The argument "-=" removes any hyphens and equals signs from both ends, leaving Title.
Not a prefix."cabbage" loses c, a, b, b, and a from the left, because each one is in the set, and stops at g. Nothing is removed from the right, since e is not in the set.
It keeps going. From the right, "banana" loses a, n, a, n, and a, and the left side stops at b, which is not in the set.
Frequently Asked Questions
It returns a copy of the string with whitespace removed from both ends. If you pass characters, it removes any of those characters from both ends instead.
No. It only works on the two ends. To remove spaces inside the text use replace(" ", "") or split() and join().
strip() trims both ends, lstrip() trims only the left end, and rstrip() trims only the right end.
The argument is a set of characters. strip("abc") removes every a, b, or c from the ends until another character appears. Use removeprefix() or removesuffix() for exact text.
No. Strings are immutable, so strip() returns a new string. Assign the result, for example text = text.strip().