Find the Longest Common Prefix String in Python

Find the longest common prefix string

To find the Longest Common Prefix string for the given two strings in Python, you can iterate over the characters, and check if the respective characters of the strings are equal. When the characters from the two strings are not equal, the substring before that character, from any of the two strings, is our required Longest Common Prefix string.

string 1 : apples
             string 2 : applications
longest common prefix : appl

Examples

1. Find the longest common prefix of “apples” and “applications”

In the following program, we take two strings: "apple", and "applications", and find their longest common prefix string.

Python Program

string1 = "apples"
string2 = "applications"
result = ""

length = min(len(string1), len(string2))

for i in range(length):
    if string1[i] != string2[i]:
        result = string1[0:i]
        break

print(result)
Run Code Copy

Output

appl

2. Find the longest common prefix of “banana” and “banking”

In this example, we take the strings: "banana", and "banking", and find their longest common prefix string.

Python Program

string1 = "banana"
string2 = "banking"
result = ""

length = min(len(string1), len(string2))

for i in range(length):
    if string1[i] != string2[i]:
        result = string1[0:i]
        break

print(result)
Run Code Copy

Output

ban

Summary

In this tutorial of Python Strings, we learned how to find the Longest Common Prefix string of the given two strings.

Related Tutorials

Code copied to clipboard successfully 👍