Home  >  Article  >  Backend Development  >  How to Find the Longest Common Substring Between Two Strings in Python?

How to Find the Longest Common Substring Between Two Strings in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 03:40:02238browse

How to Find the Longest Common Substring Between Two Strings in Python?

Finding Common Substrings in Two Strings

Identifying the common substring shared by two strings is a common task in programming. Suppose we have two input strings, as illustrated in the problem statement:

<br>string1 = "apples"<br>string2 = "appleses"<br>

In this case, the common substring is "apples". Similarly, for the more complex example:

<br>string1 = "apple pie available"<br>string2 = "apple pies"<br>

The expected output should be "apple pie", which represents the shared substring.

Pythonic Solution Using difflib

To efficiently solve this problem in Python, we can leverage the difflib module included in the standard library. Specifically, the find_longest_match() method in SequenceMatcher can be utilized to identify the longest common substring between two strings.

<code class="python">from difflib import SequenceMatcher

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

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

print(match)  # Output: Match(a=0, b=15, size=9)
print(string1[match.a:match.a + match.size])  # Output: "apple pie"
print(string2[match.b:match.b + match.size])  # Output: "apple pie"</code>

In Python versions earlier than 3.9, the find_longest_match() method requires additional arguments:

<code class="python">SequenceMatcher(None, string1, string2).find_longest_match(0, len(string1), 0, len(string2))</code>

By employing this approach, we can effectively extract the common substring from a pair of input strings, simplifying the task of finding shared sequences.

The above is the detailed content of How to Find the Longest Common Substring Between Two Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn