Start learning free

LESSON 382 OF 410 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: grep v2 — Case-Insensitive Match in Python

Practice

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

    Grep V2 in Python

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