How to find common substrings between two strings with Python?

Sometimes, we want to find common substrings between two strings with Python.

In this article, we’ll look at how to find common substrings between two strings with Python.

How to find common substrings between two strings with Python?

To find common substrings between two strings with Python, we can use the difflib module.

For instance, we write:

from difflib import SequenceMatcher

string1 = "apple pie available"
string2 = "come have some apple pies"

match = SequenceMatcher(None, string1,
                        string2).find_longest_match(0, len(string1), 0,
                                                    len(string2))

print(match)
print(string1[match.a:match.a + match.size])
print(string2[match.b:match.b + match.size])

We have 2 strings string1 and string2 that we want to find the common substring that’s in both strings.

To do that, we use the SequenceMatcher class with string1 and string2.

And we call the find_longest_match method with the indexes for both strings to search for.

Finally, we get the substring that matched from the match object, which has the start and index of the matches with match.a and match.a + match.size for the first string and match.b and match.b + match.size for the 2nd string respectively.

As a result, we see:

Match(a=0, b=15, size=9)
apple pie
apple pie

printed.

Conclusion

To find common substrings between two strings with Python, we can use the difflib module.