Start learning free

LESSON 613 OF 673 · PROJECTS: COMMAND-LINE TOOLS

grep in Python: Filtering Lines with the in Operator

Practice Read the full explanation

Build a tiny version of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring (case-sensitive), joined by newline characters (\n).

Function signature:

def grep(self, lines: List[str], pattern: str) -> str:

Example:

Input:
pattern = "err"
lines = ["error: foo", "warning", "another error", "ok"]

Output: "error: foo\nanother error"

When printed:
error: foo
another error

If no lines match, return the empty string "".

Note: real grep treats the pattern as a regular expression by default (grep -F matches plain text). Here the pattern is always plain text: just look for it literally, so characters such as . or * mean nothing special.


Iterate over the lines, keep the ones where pattern in line is true, then join with "\n".

The full solution:
class Solution:
    def grep(self, lines, pattern):
        result = []
        for line in lines:
            if pattern in line:
                result.append(line)
        return "\n".join(result)

STEP 1 OF 5
    Ctrl + Enter to check

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Grep V1 in Python, explained

    Problem overview

    This lesson builds a tiny grep. The method grep(self, lines, pattern) receives a list of strings and a search text. It returns every line that contains the pattern as a substring, in the original order, joined into one string with newline characters. The match is case-sensitive.

    With pattern = "err" and lines = ["error: foo", "warning", "another error", "ok"] the result is "error: foo\nanother error". Printed, that is two lines. If no line matches, the result is the empty string.

    The pattern is plain text. In the real tool it is a regular expression by default, but here characters such as . and * have no special meaning: the pattern "a.c" matches "a.c" and doesn't match "abc".

    Approach: filter, then join

    The job has two parts. First, decide for each line whether to keep it. Second, glue the kept lines together. Python's in operator answers the first part: pattern in line is True when the pattern appears anywhere inside line, not only at the start. For the second part, "\n".join(result) puts a newline between each two items of a list.

    Collect the kept lines in a list and join once at the end. Building the string with += would need extra care to avoid a newline at the start or the end.

    Step by step

    1. Create an empty list named result. Nothing has matched before the first line is checked.
    2. Loop over lines with for line in lines. One pass visits every line.
    3. Test pattern in line inside the loop. The check is true when the pattern occurs anywhere in the line.
    4. Append the line to result inside the if, so only lines that passed the test are kept.
    5. Return "\n".join(result) after the loop. When nothing matched, the list is empty and joining an empty list gives "", which is the result the lesson wants.

    The solution in Python

    class Solution:
        def grep(self, lines, pattern):
            result = []
            for line in lines:
                if pattern in line:
                    result.append(line)
            return "\n".join(result)
    

    The returned value is one string that contains \n characters, not a list. Calling print on it shows each kept line on its own row. The separator goes only between lines, so the result has no newline after the last line.

    The in test on strings is a substring test, and it is literal. That is why the dot in "a.c" means a dot and nothing else:

    print(repr(Solution().grep(["a.c", "abc", "Err"], "a.c")))
    print(repr(Solution().grep(["Error: 1", "ok"], "err")))
    
    'a.c'
    ''
    

    The second call returns the empty string because "err" doesn't match "Error": the capital E is part of the text, and the comparison is case-sensitive.

    Complexity

    Each in test scans one line, so the time is about O(total length of the lines) times the pattern length in the worst case, and in practice close to the total length. The result list holds references to the kept lines, so extra space is O(k) for k kept lines, plus the final joined string.

    Edge cases and common mistakes

    • No match. The result is "", not None and not a list.
    • Returning the list. Forgetting "\n".join(result) returns a list, which is not the string the lesson expects.
    • Case. "err" finds "error" but not "ERROR".
    • Matching only the start. line.startswith(pattern) would miss "another error". in finds the pattern anywhere.
    • Trailing newline. Joining with "\n" adds no newline after the last line, which is what the expected output has.
    • An indented return. Placed inside the loop, it would stop after the first line.

    Testing

    With lines = ["error: foo", "warning", "another error", "ok"]:

    patternresult
    "err""error: foo\nanother error"
    "zzz"""

    The next version builds on this one.

    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free