A Simple Guide to Python Extract the Longest Common Substring Between Two Strings – Python Tutorial

By | September 25, 2019

If there are two python strings:

s1 = 'Python logging.info() Display on Console and Save Message into File - Python Tutorial'
s2 = 'Python logging.info() Display on Console - Tutorial Example'

How to extract the longest common substring ”Python logging.info() Display on Console“? In this tutorial, we will introduce how to extract it.

Python extract the Longest Common Substring

Import library

from difflib import SequenceMatcher

Create a python function to extract longest common substring

def longest_Substring(s1,s2): 
  
     seq_match = SequenceMatcher(None,s1,s2) 
     match = seq_match.find_longest_match(0, len(s1), 0, len(s2)) 
     # return the longest substring 
     if (match.size!=0): 
          return s1[match.a: match.a + match.size]
     else: 
          None

This function can get the longest common substring between s1 and s2.

How to use this function

print("Original Substrings:")
print("s1 = "+ s1+"\ns2 = " +s2)
print("\nCommon longest sub_string:")
print(longest_Substring(s1,s2))

The longest common substring between s1 and s2 is:

Common longest sub_string:
Python logging.info() Display on Console

Leave a Reply