How to Filter a List of Strings by Keyword in Python
A helper function filters a list of strings by a keyword search with optional case sensitivity.
Python code
36 linesdef filter_strings(items, keyword, case_sensitive=False):
"""
Filter a list of strings by a keyword.
Args:
items: list of strings to filter
keyword: substring to search for
case_sensitive: if True, match case exactly
Returns:
list of strings containing the keyword
"""
if case_sensitive:
return [item for item in items if keyword in item]
else:
keyword_lower = keyword.lower()
return [item for item in items if keyword_lower in item.lower()]
if __name__ == "__main__":
sample_data = [
"Python programming",
"Data Science basics",
"python for beginners",
"Web Development",
"Machine Learning with Python"
]
print("Filter 'python' (case-insensitive):")
print(filter_strings(sample_data, "python"))
print("\nFilter 'python' (case-sensitive):")
print(filter_strings(sample_data, "python", case_sensitive=True))
print("\nFilter 'data':")
print(filter_strings(sample_data, "data"))
Output
Filter 'python' (case-insensitive):
['Python programming', 'python for beginners', 'Machine Learning with Python']
Filter 'python' (case-sensitive):
['python for beginners']
Filter 'data':
['Data Science basics']
How it works
The function uses a list comprehension to build a new list of matching strings. For case-insensitive matching, it converts both the keyword and each item to lowercase before checking the in operator. The case_sensitive parameter defaults to False, providing a convenient and safe default for most use cases. The if __name__ == "__main__" guard ensures the demo only runs when the script is executed directly, not when imported as a module.
Common mistakes
- Forgetting to lower the keyword as well as the items, leading to mismatches.
- Not considering case sensitivity requirements and always using `in` directly.
- Filtering in place and mutating the original list instead of returning a new one.
Variations
- Use `str.casefold()` instead of `.lower()` for more aggressive Unicode normalization.
- Use a regular expression with `re.search` if you need more complex pattern matching.
Real-world use cases
- Searching a list of filenames for a given extension or keyword in a file manager or CLI tool.
- Filtering log entries by a substring to isolate relevant error messages during debugging.
- Implementing a simple search feature in a small application to find items by name or description.
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.