How to Strip Whitespace from String in Python Easily
In Python, you can remove whitespace from the start and end of a string using the
strip() method. To remove whitespace only from the left or right side, use lstrip() or rstrip() respectively.Syntax
The main methods to remove whitespace from strings are:
string.strip(): Removes whitespace from both ends.string.lstrip(): Removes whitespace from the start (left side).string.rstrip(): Removes whitespace from the end (right side).
These methods return a new string without changing the original.
python
stripped_string = string.strip() left_stripped = string.lstrip() right_stripped = string.rstrip()
Example
This example shows how to use strip(), lstrip(), and rstrip() to remove whitespace from a string.
python
text = " Hello, Python! " print(f"Original: '{text}'") print(f"strip(): '{text.strip()}'") print(f"lstrip(): '{text.lstrip()}'") print(f"rstrip(): '{text.rstrip()}'")
Output
Original: ' Hello, Python! '
strip(): 'Hello, Python!'
lstrip(): 'Hello, Python! '
rstrip(): ' Hello, Python!'
Common Pitfalls
One common mistake is expecting strip() to remove spaces inside the string, but it only removes spaces at the start and end. Also, these methods do not change the original string because strings are immutable in Python.
Another pitfall is forgetting that strip() removes all whitespace characters, including tabs and newlines, not just spaces.
python
text = " Hello \tWorld\n " wrong = text.replace(" ", "") # This removes only spaces, not tabs or newlines right = text.strip() # Removes all whitespace from both ends print(f"Wrong: '{wrong}'") print(f"Right: '{right}'")
Output
Wrong: '\tWorld\n'
Right: 'Hello \tWorld'
Quick Reference
| Method | Description | Example |
|---|---|---|
| strip() | Removes whitespace from both ends | ' text '.strip() → 'text' |
| lstrip() | Removes whitespace from the start (left) | ' text '.lstrip() → 'text ' |
| rstrip() | Removes whitespace from the end (right) | ' text '.rstrip() → ' text' |
Key Takeaways
Use
strip() to remove whitespace from both ends of a string.Use
lstrip() or rstrip() to remove whitespace from only one side.These methods do not remove spaces inside the string, only at the edges.
Strings are immutable; these methods return new strings without changing the original.
Whitespace includes spaces, tabs, and newlines, all removed by these methods at the edges.