Pattern Searching in Python

In the previous article we saw how String comparison works, in this article we will see how we can deal with a common computer science problem ..we have a large text and then we have a pattern. Our task is to find all occurrences of this pattern within this large text. This is a very common problem and common in various applications. In document processors like MS-Word, e-book readers or text editors we can see a practical implementation of dealing with this problem through the find option. While the code and command line output for these implementations are hidden from us in GUI applications, the code is running a pattern matching algorithm as a background operation.

Let us discuss implementation of a simple way of pattern searching in Python, using the methods that we have discussed so far.

Implementation of Pattern Searching in Python

We have the text “Man on the roof , gazes at the stars”, and the pattern “gazes”. It should return the index of the position of ‘gazes’ within the string, in this case it would be 15. Suppose the text was “AAAAA”, and the pattern was “AAA”, it would return us the output “0 1 2”.

We can attempt to write the relevant code for this output by using the find( ) function.

txt=input("Enter Text:")
pat=input("Enter pattern: ")
pos=txt.find(pat)
while pos>=0:
    print(pos)
    pos=txt.find(pat,pos+1)
Output:
Enter Text: on the roof , gazes at the stars
Enter pattern: gazes
15

First we create provisions for the user to enter both the text and the pattern it should search for within that text input. We can use the find function to return the respective indexes where the patterns can be found and store it in a variable.

Next, we have the loop and we state in the loop that while the position is greater than or equal to zero, print the position and change the position (increased by 1). This repeats until the necessary index is obtained for the pattern.

In the next article we will look at how we can check for palindrome strings in Python.

Leave a Comment