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
str.lstrip
Returns a copy of the string with leading characters removed. Defaults to whitespace; a chars argument specifies a set of characters to strip from the left.
str.rstrip
Returns a copy of the string with trailing characters removed. Defaults to whitespace; a chars argument specifies a set of characters to strip from the right.
str.replace
Returns a new string with all occurrences of substring old replaced by new. If count is given, only the first count occurrences are replaced.
str.format
Substitutes replacement fields delimited by { } in the string with values from args and kwargs, using the Format Specification Mini-Language. In modern Python, f-strings are usually preferred for literals; str.format() remains ideal for templates loaded at runtime.
str.rjust
Returns the string right-justified in a field of the given width, padded on the left with fillchar. Returns the original string unchanged if it is already at least width characters long.