Start learning free

LESSON 14 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Case-Insensitive grep in Python with lower()

Practice Read the full explanation

Build the -i flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring, ignoring letter case. Return the matching lines joined by newline characters (\n).

Function signature:

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

Example:

Input:
pattern = "ERR"
lines = ["Error: 1", "ok"]

Output: "Error: 1"

When printed:
Error: 1

The matching is case-insensitive but the original line (preserving its original casing) is returned. If no lines match, return the empty string "". The lines contain only ASCII characters.


Lowercase BOTH the pattern and each line before comparing. Lowercase the pattern just once outside the loop. Don't lose the original line — append it (not the lowercased version) when you have a match.

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

STEP 1 OF 6
    Ctrl + Enter to check

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Grep V2 in Python, explained

    Problem overview

    This version adds the -i flag of grep. The method grepCaseInsensitive(self, lines, pattern) returns every line that contains pattern as a substring, ignoring letter case, joined with newline characters. The lines come back as they were written, with their original capitals.

    With pattern = "ERR" and lines = ["Error: 1", "ok"] the result is "Error: 1". The pattern was upper case and the line has Err, yet it matches, and the line is returned unchanged. When nothing matches, the result is "". The lesson's lines contain only ASCII characters.

    Approach: compare in one case, keep the original

    To ignore case, convert both sides to the same case before comparing. Lower case is the usual choice. The important detail is what you keep: the lower-cased copy of the line is only used for the test, and the original line goes into the result.

    The pattern is the same for every line, so lower-case it once before the loop. The line changes on every pass, so it is lower-cased inside the loop.

    print("Error: 1".lower())
    print("ERR".lower() in "Error: 1".lower())
    print("ERR" in "Error: 1")
    
    error: 1
    True
    False
    

    Without the conversion the plain in test fails, because "ERR" and "Err" are different text.

    Step by step

    1. Create the empty list result for the lines that match.
    2. Create lowerPattern with pattern.lower(). Doing it once here avoids repeating the same conversion for every line.
    3. Loop over lines, one line at a time.
    4. Test lowerPattern in line.lower(). Both sides are lower case now, so "ERR" finds "Error". The call line.lower() makes a new string and leaves line itself as it was.
    5. Append the original line to result, not the lower-cased copy. The copy was only needed for the check.
    6. Return "\n".join(result) after the loop. If nothing was kept, the list is empty and the result is "".

    The solution in Python

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

    Strings in Python are immutable, so line.lower() never changes line: it returns a new string. That is why appending line afterwards still gives the original capitals. A common slip is to call line.lower() on its own line and expect line to be different afterwards. It isn't.

    For ASCII text, lower() is all you need. Python also has casefold(), a more aggressive version meant for comparing text in other alphabets (it turns "Straße" into "strasse"), but the lesson's input is ASCII, so lower() is the right tool.

    Complexity

    Time is proportional to the total length of the lines, because each line is lower-cased once and searched once. Extra space is the list of kept lines, plus one lower-cased copy of a line at a time.

    Edge cases and common mistakes

    • Appending the lower-cased line. result.append(line.lower()) returns "error: 1" instead of "Error: 1".
    • Lowering only one side. pattern in line.lower() fails when the pattern has capitals, and lowerPattern in line fails when the line does.
    • Lowering the pattern inside the loop. The result is right but the same work is repeated for every line.
    • Expecting lower() to change in place. Strings are immutable, so the new value must be used or stored.
    • No match. Return "".

    Testing

    patternlinesresult
    "ERR"["Error: 1", "ok"]"Error: 1"
    "err"["Error: 1", "eRRor", "ok"]"Error: 1\neRRor"

    The previous version, which compared case exactly, would return "" for the first row.

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