How to Filter Empty Strings in Python

Remove empty and whitespace-only strings from a list using a list comprehension with the strip() method.

Easy Python 3.6+ Aug 9, 2026 Lists & loops 12 views 0 copies

Python code

13 lines
Python 3.6+
def filter_empty_strings(strings):
    """
    Filter out empty strings (including whitespace-only strings)
    from a list of strings.
    """
    return [s for s in strings if s.strip()]


if __name__ == "__main__":
    sample_list = ["hello", "", "world", "   ", "python", " ", "!"]
    filtered = filter_empty_strings(sample_list)
    print(f"Original list: {sample_list}")
    print(f"Filtered list: {filtered}")

Output

stdout
Original list: ['hello', '', 'world', '   ', 'python', ' ', '!']
Filtered list: ['hello', 'world', 'python', '!']

How it works

The list comprehension iterates over each string and keeps it only if s.strip() returns a truthy value. strip() removes leading and trailing whitespace, so empty strings and strings with only spaces become empty, which evaluates to False in a boolean context. This approach handles both empty strings and whitespace-only strings in one pass. The original list remains unchanged because the comprehension builds a new list.

Common mistakes

  • Using `if s` instead of `if s.strip()`—this keeps strings with only spaces.
  • Modifying the original list in place with remove() while iterating, which skips elements.
  • Forgetting to import anything—this works with the standard library.

Variations

  1. Use `filter(None, (s.strip() for s in strings))` to create a generator, but this strips the content—use `filter(lambda s: s.strip(), strings)` to preserve original strings.
  2. Use a loop with an append to build the result for readability in older Python versions.

Real-world use cases

  • Cleaning user input lists from CSV files where missing data appears as empty or whitespace cells.
  • Preprocessing log lines before analysis, removing blank lines and those containing only spaces.
  • Sanitizing form fields from a web request before storing them in a database.

Sponsored

Run this sample

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

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.