str.strip()
Python · Strings
Theory
.strip() returns a copy of a string with leading and trailing whitespace removed; spaces, tabs and newlines inside the text are kept. ' Asha Rao '.strip() gives 'Asha Rao'. .lstrip() trims only the left side and .rstrip() only the right, which is handy for removing the trailing newline from lines read from a file. Like every string method, it returns a new string and leaves the original unchanged.
When you pass an argument, it is treated as a set of characters, not as a word. Python keeps removing any of those characters from both ends until it hits one that is not in the set. So 'xxhixx'.strip('x') gives 'hi', but 'www.site.com'.strip('w.com') gives 'site', because w, ., c, o and m are all stripped from both ends. To remove an exact prefix or suffix, use .removeprefix() or .removesuffix() instead.
Why we use it
Stray spaces are invisible but break comparisons and joins: 'Asha ' is not equal to 'Asha'. Stripping is the first cleaning step for user input, CSV fields and lines read from files.
When to use it
Strip text fields right after reading them and before comparing, grouping or converting with int() or float(). Use rstrip('\n') for file lines. Use replace(' ', '') if you need to remove spaces inside the text too.
How it works
- Call s.strip()
- Look at the first character
- Is it whitespace (or in the given chars)? Yes: Drop it and check the next one. No: Stop trimming the left side.
- Repeat the same check from the right end
- Return the new trimmed string
Syntax
string.strip()
string.strip(chars)Example
name = ' Asha Rao '
print(name.strip())Key points
- lstrip()/rstrip() trim only the left/right side
- Spaces inside the text are not removed
- strip('abc') removes any of a, b, c from the ends, not the word 'abc'
- Use removeprefix()/removesuffix() to drop an exact piece
- Commonly used to clean user input or CSV-imported text