Content · Programming · Python

Python difflib.SequenceMatcher: Compare Text Sequences

Compare sequences and estimate similarity with difflib.SequenceMatcher.

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

Compare sequences and estimate similarity with difflib.SequenceMatcher.

How It Works


SequenceMatcher identifies matching blocks between hashable sequences and offers a ratio between zero and one. The ratio is a heuristic similarity measure, not an edit distance or security check.

Step-by-Step Example


from difflib import SequenceMatcher
first_text = 'account'
second_text = 'accounts'
match_ratio = SequenceMatcher(None, first_text, second_text).ratio()
print(0 < match_ratio < 1)

Understanding the Example


  • The expression "'account'" supplies the value stored as 'first_text'. This value is then used or checked by the later statements.
  • The expression "'accounts'" supplies the value stored as 'second_text'. This value is then used or checked by the later statements.

A successful run of this example prints the following output:

True

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


The autojunk heuristic can affect large repetitive sequences.

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 a similarity ratio as proof two records describe the same real-world identity.
  • Rank several spelling suggestions by their similarity to a search term.

Key Takeaways


  • Compare sequences and estimate similarity with difflib.SequenceMatcher.
  • SequenceMatcher identifies matching blocks between hashable sequences and offers a ratio between zero and one.
  • 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.