Content · Programming · Python

Python difflib.get_close_matches() Function: Usage and Examples

Find close string matches for suggestions and typo recovery.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Find close string matches for suggestions and typo recovery.

How It Works


difflib.get_close_matches(word, possibilities, n=3, cutoff=0.6) returns a ranked list of similar strings. Increase cutoff to reduce loose suggestions; fuzzy matching should not silently authorize a different account or operation.

Step-by-Step Example


import difflib
known_words = ['database', 'dashboard', 'developer']
print(difflib.get_close_matches('databse', known_words, n=2))

Understanding the Example


  • The expression "['database', 'dashboard', 'developer']" supplies the value stored as 'known_words'. This value is then used or checked by the later statements.
  • The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.

A successful run of this example prints the following output:

['database']

Where This Fits in a Real Program


Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.

Practice: Try It Yourself


Adjust cutoff based on the cost of false matches.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Using fuzzy matches as exact identifiers in security-sensitive or billing operations.
  • Suggest likely commands when a user mistypes a known option.

Key Takeaways


  • Find close string matches for suggestions and typo recovery.
  • difflib.get_close_matches(word, possibilities, n=3, cutoff=0.6) returns a ranked list of similar strings.
  • Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.
Share this resourceSend this page to someone who may find it useful.