pandas: Filter rows by a keyword

Model df[df["comment"].str.contains(word, case=False, na=False, regex=False)]: keep the rows whose text contains a keyword.

What to build

A program that filters text rows by a keyword, ignoring case and missing values.

Requirements

  • A row matches when its text contains the keyword, ignoring upper and lower case. A row whose text is exactly NA is missing and does not match.
  • For each matching row print I: TEXT, where I is the row's position counting from 0, then print matches K.

Input

Line 1: the keyword. Line 2: n. Then n lines of text.

Output

One line per match, then one line.

Constraints

1 ≤ n ≤ 1000; the keyword is not empty.

Example

Input:

late
4
Delivery was LATE
on time
NA
Slightly late again

Output:

0: Delivery was LATE
3: Slightly late again
matches 2

Why it works

Lowering both sides makes the test case-insensitive, and treating missing values as False keeps the mask purely boolean so it can select rows.

Examples

Example 1 · Input
late
4
Delivery was LATE
on time
NA
Slightly late again
Expected output
0: Delivery was LATE
3: Slightly late again
matches 2
Example 2 · Input
x
1
abc
Expected output
matches 0

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Lower both the text and the keyword before testing with in.

Hint 2

A line that is exactly NA is a missing value and never matches.

Solution

Show one correct solution (try it yourself first)
word = input().lower()
n = int(input())
lines = [input() for _ in range(n)]
hits = [(i, t) for i, t in enumerate(lines) if t != "NA" and word in t.lower()]
for i, t in hits:
    print(f"{i}: {t}")
print("matches", len(hits))

Lesson: Working with text columns →