To search through a text means to iterate through it and check each character based on some criteria.

With our naive pattern search, we will:

  • Iterate through each character of the text.
  • For each character of the text, count the number of following characters that match the pattern.
  • Check if that match count equals the length of the pattern.

If the match count equals the length, then a pattern has been found!

In this first exercise we will tackle iterating through the text and pattern.



At the top of the code editor, define a function called pattern_search. Give pattern_search two parameters: text and pattern, and have it print both inputs.

Below the initialized variables, text and pattern, invoke pattern_search with these two variables passed in as arguments.


Inside your function, after the print statement, use a for loop to iterate over the indices of the text, printing each index with a label such as "Text Index:" to keep things tidy.


For each iteration of the text indices, loop through all of the indices of the pattern, and individually print those char indices with the label "Pattern Index:".

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?