Home > OS >  How to find a common substring between two strings in python?
How to find a common substring between two strings in python?

Time:03-31

I have two strings

str1 = "SA-Power Systems, Ltd."
str2 = "sa-power"

Now I want to know if there exists any similarity between the two strings. So I could do something like below

from re import search, IGNORECASE

str1 = "SA-Power Systems, Ltd."
str2 = "sa-power"

if search(str1, str2, IGNORECASE):
    print "Found!"
else:
    print "Not found!"

So I get a match. However if I do a vice versa (replace str1 with str2 and str2 with str1), then I get no match. Is there a way in python to quickly check for similarity between two strings?

CodePudding user response:

No need to use re in this case, as it is enough to .lower() both to get case-insensitive comparison i.e.

str1 = "SA-Power Systems, Ltd."
str2 = "sa-power"
if str1.lower() in str2.lower() or str2.lower() in str1.lower():
    print("Found")
else:
    print("Not found")

output

Found

CodePudding user response:

Re.search looks for a pattern and all of the pattern needs to be present for it to be true. You could get around this problem by making sure both the strings are the same length with something like:

from re import search, IGNORECASE

str1 = "SA-Power Systems, Ltd."
str2 = "sa-power"

if search(str1[:len(str2)], str2, IGNORECASE):
    print ("Found!")
else:
    print ("Not found!")

With that said if you want to search the whole string and not just the first x digits then you could add a conditional statement that switches the smaller string in the first position(without the indexing) of the search argument.

  • Related