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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 14 views 0 copies

Python code

8 lines
Python 3.9+
def 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

stdout
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

  1. Use `lstrip()` to remove only leading whitespace.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.