How to Strip Whitespace in Python
This code demonstrates how to remove leading and trailing whitespace from a string using the built-in strip() method.
Python code
8 linesdef strip_whitespace(text: str) -> str:
return text.strip()
if __name__ == "__main__":
sample = " Hello, world! "
result = strip_whitespace(sample)
print(f"Original: '{sample}'")
print(f"Stripped: '{result}'")
Output
Original: ' Hello, world! '
Stripped: 'Hello, world!'
How it works
The strip() method is a core string method that removes any whitespace characters from the beginning and end of a string. It works without any arguments by default, but you can pass a string of characters to remove specific ones. The method returns a new string, leaving the original unchanged, which is typical for string operations in Python. This is a simple and efficient way to clean user input or data before further processing.
Common mistakes
- Using `strip()` without checking the original string is immutable - it returns a new string, not modifying in place.
- Confusing `strip()` with `lstrip()` or `rstrip()` which only remove from one side.
- Forgetting that `strip()` removes all whitespace characters including tabs and newlines, not just spaces.
Variations
- Use `lstrip()` to remove only leading whitespace.
- Use `rstrip()` to remove only trailing whitespace.
Real-world use cases
- Cleaning user input from forms or command-line arguments before validation.
- Trimming whitespace from CSV fields when processing imported data.
- Normalizing text in log parsing to ensure consistent matching.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.