如何用Python找到兩個字串中最長的公共子字串?

Linda Hamilton
發布: 2024-10-28 12:12:02
原創
872 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!