Python Reference ยท String Methods
Python str.strip() method
Reference for Python str.strip(): remove leading and trailing whitespace or any characters from a set, plus lstrip(), rstrip() and common mistakes.
The str.strip() method returns a copy of the string with leading and trailing characters removed. With no argument it removes whitespace: spaces, tabs, newlines and other Unicode whitespace. With an argument, it removes any characters found in that argument.
It is the usual way to clean user input and lines read from files. Only the ends are affected; whitespace inside the string stays as it is.
print(" hi there \n".strip() + "|") # hi there|
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.strip() str.strip(chars)
| Name | Description |
|---|---|
chars |
Optional. A string whose characters are all removed from both ends, in any order. None or omitted means whitespace. |
Return value: a new string.
Raises: TypeError if chars is neither a string nor None.
Usage notes
- A set of characters, not a substring.
"abcba".strip("ab")gives"c"because every leading and trailingaorbis removed. For an exact prefix or suffix useremoveprefix()andremovesuffix(). - Stops at the first non-matching character from each end; the middle is never touched.
- Only the ends. To collapse inner whitespace, use
" ".join(s.split()). - One side only:
lstrip()(leading) andrstrip()(trailing). - What counts as whitespace follows Unicode, so non-breaking spaces (
\xa0) are removed too, while zero-width spaces are not. - Strings are immutable. Assign the result.
- Tidy a parse: strip before converting, as in
int(text.strip()), althoughint()already ignores surrounding whitespace. - Also on
bytesandbytearray.