首页  >  文章  >  后端开发  >  如何用Python找到两个字符串中的最长公共子串?

如何用Python找到两个字符串中的最长公共子串?

Linda Hamilton
Linda Hamilton原创
2024-10-28 12:12:02863浏览

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

使用 Python 查找两个字符串中的公共子字符串

在 Python 中,可以使用以下方法轻松实现比较两个字符串并提取匹配的子字符串difflib 模块的 find_longest_match 方法。此方法自 Python 3.9 起可用,返回两个序列的最长公共子字符串,包括字符串。

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

string1 = "apple pie available"
string2 = "apple pies"

match = SequenceMatcher(None, string1, string2).find_longest_match()
print(string1[match.a:match.a + match.size])  # "apple pie"
print(string2[match.b:match.b + match.size])  # "apple pie"</code>

如果您使用 3.9 之前的 Python 版本,可以使用以下参数调用 find_longest_match:

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

在提供的示例中,输入字符串具有重叠的子字符串(“苹果派”),这是使用 find_longest_match 准确提取的。这种多功能方法可以处理不同长度和复杂性的字符串,使其成为 Python 中字符串比较任务的宝贵工具。

以上是如何用Python找到两个字符串中的最长公共子串?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn