Categories
Python Answers

How to find the similarity metric between two strings with Python?

Spread the love

Sometimes, we want to find the similarity metric between two strings with Python.

In this article, we’ll look at how to find the similarity metric between two strings with Python.

How to find the similarity metric between two strings with Python?

To find the similarity metric between two strings with Python, we can use the difflib module.

For instance, we write:

from difflib import SequenceMatcher


def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()


s = similar("Apple", "Apelp")
print(s)

We define the similar that takes 2 strings a and b.

In the function, we create the SequenceMatcher instance with the 2 strings.

And we call ratio to return the similarly ratio between a and b.

Then we call similar with 2 strings and assign the returned result to s.

Therefore, s is 0.6.

Conclusion

To find the similarity metric between two strings with Python, we can use the difflib module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *