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

ParameterDescription
chars optional A set of characters to remove from both ends. Default: whitespace.

Return value

A new string.

Examples

Trim whitespaceTry it yourself
print(repr("  hello world \n".strip()))

Output

'hello world'
Strip specific charactersTry it yourself
print("**Sale!**".strip("*!"))
print("xxhixx".strip("x"))

Output

Sale
hi
Clean up user inputTry it yourself
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

VersionChange
Python 3.0Added