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.

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

Python code

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

stdout
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

  1. Use `str.casefold()` instead of `.lower()` for more aggressive Unicode normalization.
  2. 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

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.