Python difflib — Close Matches, Ratios, and Diffs
Programs often need to answer three questions about text: how alike are these two pieces, which known word did the user almost type, and what exactly changed between these two versions. The difflib module answers all three with one matcher, a close-match helper, and two diff formats. This guide takes the ratio first, then close matches, the two diffs, opcodes, word-level comparison, and the input traps.
Written November 13, 2026 · Tested with Python 3.12.3 · 9 min read
- The main program: the ratio and the matching blocks
- getclosematches: the closest words to a guess
- unifieddiff: a diff with headers
- ndiff and restore: a plainer diff
Written November 13, 2026
Tested with Python 3.12.3
What this guide is
The difflib module compares sequences. Give it two strings and it works character by character; give it two lists and it works item by item. One class, SequenceMatcher, does the core work and reports a similarity ratio, the blocks that match, and a list of edit steps that would turn the first sequence into the second. Two helpers sit on top of it: get_close_matches picks the closest candidates from a list of words, and the diff functions format a comparison as lines a person can read. Every result in this guide is a plain value the program can also use, not just text to print.
The main program: the ratio and the matching blocks
A matcher takes the two sequences and reports ratio, a number from 0 to 1. The ratio counts the characters in the matching blocks, doubled, over the total length of both inputs, so identical inputs score 1.0 and inputs with nothing in common score 0.0. The matching blocks list each run the two share, in order, and end with a zero-size block that marks the end:
import difflib
m = difflib.SequenceMatcher(None, "kitten", "sitting")
print(round(m.ratio(), 4))
print(m.get_matching_blocks())
print(difflib.SequenceMatcher(None, "abcd", "abcd").ratio())
print(difflib.SequenceMatcher(None, "abcd", "wxyz").ratio())
The exact output:
0.6154
[Match(a=1, b=1, size=3), Match(a=5, b=5, size=1), Match(a=6, b=7, size=0)]
1.0
0.0
The first block says the three characters starting at index 1 in each string match, the itt inside both words. The second block is the single n near the end. A ratio is a rough measure of likeness, useful for ranking candidates or for a threshold the program sets itself. It is not a count of edits and not a percentage of correctness, and two different pairs can share a ratio for different reasons. Code that needs the actual changes reads the opcodes, covered below.
get_close_matches: the closest words to a guess
get_close_matches scores each candidate in a list against one word and returns the best of them, best first. The n argument caps how many come back, at 3 by default, and cutoff sets the lowest ratio a candidate needs, at 0.6 by default. A word with no candidate at the cutoff returns an empty list:
import difflib
words = ["apple", "apply", "apricot", "banana", "grape"]
print(difflib.get_close_matches("appel", words))
print(difflib.get_close_matches("appel", words, n=1))
print(difflib.get_close_matches("appel", words, cutoff=0.9))
print(difflib.get_close_matches("zebra", words))
The exact output:
['apply', 'apple', 'grape']
['apply']
[]
[]
The misspelling appel returns three candidates because grape also clears the 0.6 cutoff; raising the cutoff to 0.9 clears the list entirely. This is the helper behind did-you-mean prompts, command suggestions, and search boxes that forgive a typo. The order is best match first, so code that offers one suggestion takes the first item and code that offers a menu shows the list as returned. An empty list is a normal result, and callers handle it as no suggestion rather than as an error.
unified_diff: a diff with headers
A unified diff is the format patch tools and code reviews use. It opens with a header naming the two sides, then shows each change in a hunk: lines starting with a space are unchanged context, a minus line leaves, and a plus line arrives. The inputs are lists of lines, and each line carries its own newline ending:
import difflib
before = ["one\n", "two\n", "three\n", "four\n"]
after = ["one\n", "two changed\n", "three\n", "five\n"]
diff = difflib.unified_diff(before, after, fromfile="before.txt", tofile="after.txt")
print("".join(diff), end="")
The exact output:
--- before.txt
+++ after.txt
@@ -1,4 +1,4 @@
one
-two
+two changed
three
-four
+five
The function returns an iterator of lines, so the join builds the whole text at once; writing the lines to a file one by one works just as well. The fromfile and tofile names are labels only and default to empty strings. The hunk header @@ -1,4 +1,4 @@ gives the start line and the line count for each side, which is what lets a reader or a patch tool place the change. A pair of inputs with no differences yields nothing at all — the iterator is empty, header lines included.
ndiff and restore: a plainer diff
The ndiff format drops the headers and the hunk markers and marks every line: two spaces for a line present on both sides, a minus for a line only in the first input, and a plus for a line only in the second. Because each output line names which side it belongs to, the restore function can rebuild either input from the diff alone:
import difflib
before = ["keep", "drop", "change me"]
after = ["keep", "change this", "added"]
diff = list(difflib.ndiff(before, after))
print("\n".join(diff))
print(list(difflib.restore(diff, 1)))
print(list(difflib.restore(diff, 2)))
The exact output:
keep
- drop
- change me
+ change this
+ added
['keep', 'drop', 'change me']
['keep', 'change this', 'added']
Restoring side 1 keeps the context lines and the minus lines and drops the plus lines; restoring side 2 does the reverse. The diff itself is an iterator, so the program stores it in a list first and uses it twice. This format suits a report a person reads top to bottom, where each line of both versions appears once and the change is the marker at the edge.
Opcodes: the changes as data
get_opcodes returns the edit steps as tuples of a tag and four indexes. The tag is one of equal, delete, insert, or replace, and the indexes slice the matching part out of each input: a[i1:i2] and b[j1:j2]. Reading the slices beside the tag states each change in words:
import difflib
m = difflib.SequenceMatcher(None, "qabxcd", "abycdf")
print(m.get_opcodes())
for tag, i1, i2, j1, j2 in m.get_opcodes():
print(tag, "qabxcd"[i1:i2], "->", "abycdf"[j1:j2])
print(m.find_longest_match(0, 6, 0, 6))
The exact output:
[('delete', 0, 1, 0, 0), ('equal', 1, 3, 0, 2), ('replace', 3, 4, 2, 3), ('equal', 4, 6, 3, 5), ('insert', 6, 6, 5, 6)]
delete q ->
equal ab -> ab
replace x -> y
equal cd -> cd
insert -> f
Match(a=1, b=0, size=2)
A delete or an insert has an empty slice on one side, which is why those two lines show a blank on one side of the arrow. The find_longest_match call returns the single longest matching block, here ab at index 1 of the first string and index 0 of the second. Opcodes are the form to use when the program itself acts on the comparison: highlighting the changed spans, building an edit script, or counting how much of a text moved.
Comparing words instead of characters
A matcher accepts any two sequences of hashable items, so splitting two sentences into word lists compares word by word. The opcodes then speak in word indexes, and a swapped word shows as one replace step. The same pair compared as raw strings scores a different ratio, because the unit changed:
import difflib
a = "the quick brown fox jumps"
b = "the quick red fox leaps"
ma = difflib.SequenceMatcher(None, a.split(), b.split())
print(ma.get_opcodes())
mb = difflib.SequenceMatcher(None, a, b)
print(round(mb.ratio(), 4))
print(round(ma.ratio(), 4))
The exact output:
[('equal', 0, 2, 0, 2), ('replace', 2, 3, 2, 3), ('equal', 3, 4, 3, 4), ('replace', 4, 5, 4, 5)]
0.75
0.6
The word view finds two clean replace steps, brown for red and jumps for leaps, where the character view spreads the same change across many small matches. Pick the unit that matches the question: lines for files, words for sentences, characters for short strings and codes. A list of lines from a file is the most common input of all, and it follows the same rule with the line as the unit.
The traps: one string, missing newlines, and the empty pair
import difflib
print(list(difflib.unified_diff("ab", "ac")))
print(difflib.SequenceMatcher(None, "", "").ratio())
before = ["one", "two", "three"]
after = ["one", "two changed", "three"]
print("".join(difflib.unified_diff(before, after, lineterm="")))
The exact output:
['--- \n', '+++ \n', '@@ -1,2 +1,2 @@\n', ' a', '-b', '+c']
1.0
--- +++ @@ -1,3 +1,3 @@ one-two+two changed three
The fixes match the causes. Split text into lines before diffing, with splitlines on a string or the line list a file read gives. Treat an empty input as its own case before trusting a ratio. Keep the newline at the end of each input line, as a file read returns it, and the diff prints one change per line.
Which choice for which job
| Job | Choice | Why |
|---|---|---|
| Rank how alike two texts are | ratio |
One number from 0 to 1 |
| Suggest a word for a typo | get_close_matches |
Best candidates first |
| A diff for a patch or review | unified_diff |
Headers plus hunk ranges |
| A diff a person reads in full | ndiff |
Every line, one marker |
| Rebuild one side of a diff | restore |
Keeps one side's lines |
| Act on the changes in code | get_opcodes |
Each edit as data |
| Compare sentences | Word lists | One step per word swap |
Checklist
- Pass the diff functions a list of lines, never one plain string, unless a character diff is the goal.
- Keep the newline ending on each diff input line so the output prints one line at a time.
- Read
ratioas a rough likeness score, set the threshold in the calling code, and handle the empty-input case first. - Set
nandcutoffonget_close_matchesfor the job at hand, and handle its empty list as no suggestion. - Store an
ndiffresult in a list before using it twice, since the diff is an iterator. - Pick the comparison unit, characters, words, or lines, before reading anything into the result.
Related guides on this site
- Python strings — slicing and methods — the string handling that splits text into the lines and words this guide compares.
- Python regular expressions — pattern matching, the other main way to work with text that almost matches.
- Python files — open, read, and write — reading a file as a list of lines, the input the diff functions expect.
Sources
- Python Standard Library,
difflib—SequenceMatcher,get_close_matches,unified_diff,ndiff,restore, opcodes, and the ratio definition.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.