Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Filter rows without Space Strings
When working with nested lists containing strings, you might need to filter out rows that contain any strings with spaces. Python provides several approaches to accomplish this task using list comprehensions and string checking methods.
Using Regular Expressions
The most robust approach uses the re module to search for whitespace characters ?
import re
data = [["python is", "fun"], ["python", "good"], ["python is cool"], ["love", "python"]]
print("The original list is:")
print(data)
result = [row for row in data if not any(bool(re.search(r"\s", element)) for element in row)]
print("Rows without space strings:")
print(result)
The original list is: [['python is', 'fun'], ['python', 'good'], ['python is cool'], ['love', 'python']] Rows without space strings: [['python', 'good'], ['love', 'python']]
Using the 'in' Operator
A simpler approach uses Python's built-in string checking ?
data = [["python is", "fun"], ["python", "good"], ["python is cool"], ["love", "python"]]
print("The original list is:")
print(data)
result = [row for row in data if not any(" " in element for element in row)]
print("Rows without space strings:")
print(result)
The original list is: [['python is', 'fun'], ['python', 'good'], ['python is cool'], ['love', 'python']] Rows without space strings: [['python', 'good'], ['love', 'python']]
Using isspace() Method
To filter rows that don't contain strings with only whitespace characters ?
data = [["hello", "world"], [" ", "test"], ["python", "code"], [" "]]
print("The original list is:")
print(data)
result = [row for row in data if not any(element.isspace() or " " in element for element in row)]
print("Rows without space-containing strings:")
print(result)
The original list is: [['hello', 'world'], [' ', 'test'], ['python', 'code'], [' ']] Rows without space-containing strings: [['python', 'code']]
Comparison
| Method | Performance | Best For |
|---|---|---|
| Regular Expression | Slower | Complex whitespace patterns |
| 'in' Operator | Faster | Simple space detection |
| isspace() | Medium | Whitespace-only strings |
How It Works
The solution uses list comprehension with the any() function and not operator. For each row, it checks if any string element contains spaces. If no spaces are found in any element of the row, that row is included in the result.
Conclusion
Use the 'in' operator method for simple space detection as it's the most efficient. Regular expressions provide more flexibility for complex whitespace patterns but with slower performance.
