How to strip whitespace from a string in Python
Use s.strip() to remove leading and trailing whitespace, s.lstrip() for left, s.rstrip() for right.
text = " Hello, World! \n"
clean = text.strip()
print(f"Original:{repr(text)}")
print(f"Stripped:{repr(clean)}")The snippet assigns a string containing leading, trailing spaces and a newline to text, then calls the built‑in str.strip() method which returns a new string with all whitespace characters removed from both ends. The result is stored in clean and printed using f‑strings, demonstrating the before/after values. str.strip() is implemented in C, runs in O(n) time and handles all Unicode whitespace, making it the fastest and most reliable way to trim strings. A common gotcha is that strip only affects the ends; internal spaces remain unchanged, so use split‑join if you need to collapse them.
Variations
Regex alternative
import re
text = " Hello, World! \n"
clean = re.sub(r'^\s+|\s+$', '', text)
print(repr(clean))Regex works but is slower and harder to read than the built‑in strip.
Strip specific characters safely
text = "\ufeff data \n"
clean = text.strip("\ufeff \n")
print(repr(clean))Provide the characters to strip when you need to remove BOM or custom whitespace without affecting other leading characters.
Collapse internal whitespace
text = " Hello, World! \n"
normalized = " ".join(text.split())
print(repr(normalized))split() removes all whitespace runs, then join inserts a single space, useful for cleaning user input.
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.