Use .find() to search inside strings and the in operator to check membership. You write more code this lesson!
.find() to locate a substring and get its position (or -1 if not found)in operator to check if a string contains a substringif statements with string searchingType a word to search for inside a string. See exactly how .find() works!
position = my_string.find("search_word")
input.txt in the same folder as your Python file.
The island of Jersey is beautiful Python is a great programming language I love computer science at school Jersey has amazing beaches and cliffs My favourite subject is not island studies Programming in Python makes me happy The Channel Islands include Jersey and Guernsey GCSE exams start in May
Complete the code. This time you have fewer hints โ think carefully!
This code has 3 bugs. Click each underlined section to reveal the fix.
Write a Python program that reads input.txt and writes only the lines that contain the word "island" (case-insensitive โ hint: convert to lower first!) to output.txt. Print how many matching lines were found.
line.lower() then use if "island" in line_lower:count = 0 before the loop, then count += 1 each time you find a match.def keyword. This helps us:# Define a subroutine to search for a word in a line def search_line(line, keyword): position = line.lower().find(keyword.lower()) if position != -1: print(f"Found '{keyword}' at position {position} in: {line}") return True else: return False # Main program โ uses the subroutine input_file = open("input.txt", "r") count = 0 for line in input_file: line = line.strip() if search_line(line, "Jersey"): count += 1 print(f"\nTotal matches: {count}") input_file.close()
def search_line(line, keyword): โ defines a function with parametersreturn True โ sends a value back to where the function was calledsearch_line(line, "Jersey") โ calls the function with argumentss = "hello"; s.find("ll") return?"cat".find("dog") return?line?.find() case-sensitive? What does "Hello".find("hello") return?What does each snippet print? Think carefully before clicking!
sentence = "I love Python"
pos = sentence.find("love")
print(pos)word = "Hello"
print("hello" in word)def check(text, word):
return word in text.lower()
result = check("Hello World", "hello")
print(result)Write a program that uses a subroutine to search for multiple keywords in each line of input.txt. The subroutine should take a line and a keyword, and return True/False.
Your program should:
1. Define a def search(line, keyword) subroutine
2. Ask the user for 3 different keywords using input()
3. Read each line from input.txt
4. Call the subroutine for each keyword on each line
5. Write matching lines to output.txt with which keyword was found
6. Print a summary: how many matches for each keyword
line.lower() inside the subroutine for case-insensitive matching.