
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
SequenceMatcher in Python for Longest Common Substring.
Given two strings, our task is to print the longest common sub-string. We will solve problem in python using SequenceMatcher.find_longest_match () method.
Class difflib.SequenceMatcher is a flexible class for comparing pairs of sequences of any type, so long as the sequence elements are hashable.
find_longest_match(a, x, b, y)
Find longest matching block in a[a:x] and b[b:y].
Examples
Input: str1 = "pythonprogramming", str2 = "pro" Output: pro
Algorithm
Step 1: Enter two string. Step 2: initialize SequenceMatcher object with the input string. Step 3: find the match of longest sub-string output. Step 4: print longest substring.
Example Code
# Python program to find Longest Common Sub-string from difflib import SequenceMatcher def matchsubstring(m,n): seqMatch = SequenceMatcher(None,m,n) match = seqMatch.find_longest_match(0, len(m), 0, len(n)) if (match.size!=0): print ("Common Substring ::>",m[match.a: match.a + match.size]) else: print ('No longest common sub-string found') # Driver program if __name__ == "__main__": X = input("Enter first String ") Y = input("Enter second String ") matchsubstring(X,Y)
Output
Enter first String pythonprogramming Enter second String pro Common Substring ::> pro
- Related Articles
- Longest Palindromic Substring in Python
- Program for longest common directory path in Python
- Program to find length of longest common substring in C++
- How to find the longest common substring from more than two strings in Python?
- Program to print the longest common substring using C++
- Longest Common Prefix in Python
- Finding the longest common consecutive substring between two strings in JavaScript
- Python Program to Find Longest Common Substring using Dynamic Programming with Bottom-Up Approach
- Longest Substring Without Repeating Characters in Python
- Swap For Longest Repeated Character Substring in C++
- Program to find longest awesome substring in Python
- C++ Program for Longest Common Subsequence
- Java Program for Longest Common Subsequence
- Longest Palindromic Substring
- Find longest consecutive letter and digit substring in Python

Advertisements