How to find common substrings between two Strings with Python?

Estimated read time 2 min read

To find common substrings between two strings in Python, you can use various approaches such as brute force, dynamic programming, or utilizing built-in string methods. Here’s an example using the brute force approach:

def find_common_substrings(string1, string2):
    common_substrings = []
    for i in range(len(string1)):
        for j in range(i + 1, len(string1) + 1):
            substring = string1[i:j]
            if substring in string2 and substring not in common_substrings:
    return common_substrings

# Example usage
string1 = "abcdef"
string2 = "xyzdefabc"

common_substrings = find_common_substrings(string1, string2)

In this example, we define a function find_common_substrings that takes two strings as input.

Inside the function, we use two nested loops to generate all possible substrings of string1. For each substring, we check if it exists in string2 using the in operator. If a common substring is found and not already present in the common_substrings list, we add it to the list.

After iterating through all possible substrings, the function returns the common_substrings list.

In the example usage, we find the common substrings between string1 and string2 and print the result.

Note that the brute force approach has a time complexity of O(n^3) in the worst case, where n is the length of the input strings. If you need a more efficient solution, you can explore other algorithms such as dynamic programming or using built-in methods like str.find() or regular expressions (re module) for pattern matching.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply