Python 3 reference · String Methods
Python String strip() Method
Return a copy with leading and trailing characters removed: whitespace by default, or any of the characters you pass.
Python 3 Since 3.0
Syntax
str.strip(chars=None)
Parameters
| Parameter | Description |
|---|---|
chars optional |
A set of characters to remove from both ends. Default: whitespace. |
Return value
A new string.
Examples
print(repr(" hello world \n".strip()))
Output
'hello world'
print("**Sale!**".strip("*!"))
print("xxhixx".strip("x"))
Output
Sale hi
raw = [" Ada ", "Linus\n", " Grace"]
print([name.strip() for name in raw])
Output
['Ada', 'Linus', 'Grace']
Good to know
strip() only touches the ends: spaces between words stay. To collapse inner spaces use
" ".join(text.split()).
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
str.lstrip()· Return a copy with leading characters removed: whitespace by default, or any of the characters you pass.str.rstrip()· Return a copy with trailing characters removed: whitespace by default, or any of the characters you pass.str.removeprefix()· Return the string without the given prefix if it starts with it; otherwise return it unchanged.str.isspace()· Return True if every character is whitespace (spaces, tabs, newlines) and the string isn't empty.- Python Strings · tutorial