How to Filter Empty Strings in Python
Remove empty and whitespace-only strings from a list using a list comprehension with the strip() method.
Python code
13 linesdef 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
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
- 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.
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.