DEV Community

Kelvin Wangonya
Kelvin Wangonya

Posted on • Originally published at wangonya.com on

8 3

difflib - Finding close matches of strings from a list

Say we have a list of strings: _list = [...,] and user input _input = '...', how do we find the items in _list that most closely resemble _input?

Python has a built-in package called difflib with the function get_close_matches() that can help us.

get_close_matches(word, possibilities, n, cutoff) accepts four parameters:

  • word - the word to find close matches for in our list
  • possibilities - the list in which to search for close matches of word
  • n (optional) - the maximum number of close matches to return. Must be > 0. Default is 3.
  • cutoff (optional) - a float in the range [0, 1] that a possibility must score in order to be considered similar to word. 0 is very lenient, 1 is very strict. Default is 0.6.

An example from the docs:

Python 3.7.3

>>> from difflib import get_close_matches
>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
['apple', 'ape']
Enter fullscreen mode Exit fullscreen mode

The above example can easily be modified to use a custom list _list for possibilities and user input _input for word.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (2)

Collapse
 
mauroscianca98 profile image
mascIT

I'mma add this 100% on my SmartCoding app.

Collapse
 
wangonya profile image
Kelvin Wangonya

Awesome!

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay