formatting

str.strip

Returns a copy of the string with leading and trailing whitespace removed. If chars is given, removes any leading/trailing characters that appear in the chars set (not a prefix/suffix — it is a character set).

str.strip([chars])

Parameters

Parameter Purpose
chars string of characters to strip (treated as a set); default is whitespace
returns new str with both ends trimmed (original unchanged — str is immutable)

Examples

>>> '  hello  '.strip()
'hello'

removes both ends

>>> '\n\thello\n'.strip()
'hello'

tabs and newlines count as whitespace

>>> 'xxhelloxy'.strip('xy')
'hello'

chars is a set — strips any of 'x','y' from either end

>>> 'https://example.com/'.strip('/')
'https://example.com'

only affects both ends, not the middle

Gotcha

chars is a character SET, not a substring — 'ababcabab'.strip('ab') is 'c'. Use removeprefix/removesuffix (3.9+) to remove exact strings.

Related methods

← All Python string methods · Python built-ins