difflib — sequence comparison and diffs

difflib.SequenceMatcher.ratio, the automatic junk heuristic, get_close_matches, and unified_diff line terminators, checked on Python 3.13.12.

模块页正文目前为英文。

The difflib module compares sequences and can produce human-readable deltas, including unified diffs. SequenceMatcher works on any hashable sequence elements, not only strings. This page does not rewrite the built-in str methods or the re module.

SequenceMatcher.ratio() returns 2.0*M/T, where M is the number of matches and T is the total number of elements in both sequences. That is a measure of sequence similarity, not a judgement of meaning. "car" and "automobile" score low even though a reader may treat them as related.

Examples were run against Python 3.13.12. They do not open a browser diff view, and they do not claim to reproduce the site's visual tools.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

ratio, autojunk, and close matches

The default autojunk=True heuristic treats popular elements as junk when the second sequence is at least 200 elements long and an element accounts for more than 1% of it (n // 100 + 1 occurrences). Popularity is not a semantic category. Turning the heuristic off can change which blocks are treated as matches, and therefore can change ratio(), even when the two sequences are unchanged.

get_close_matches uses SequenceMatcher and returns up to n possibilities whose similarity is at least cutoff, most similar first. The scores are the same kind of sequence ratio, not a dictionary of synonyms.

SequenceMatcher.ratio, autojunk, and get_close_matches

difflib.SequenceMatcher(isjunk=None, a='', b='', autojunk=True)
SequenceMatcher.ratio()
difflib.get_close_matches(word, possibilities, n=3, cutoff=0.6)

ratio() is 2*M/T over matching elements. It is not a semantic difference. autojunk can change that number on long sequences with a popular element.

ParameterDescription
isjunkOptional callable that marks an element as junk, or None for no user-defined junk.
a, bThe two sequences to compare. Their elements must be hashable.
autojunkIf True (the default), popular elements in a sufficiently long second sequence are treated as junk. Pass False to disable the heuristic.
word, possibilitiesget_close_matches compares word with each item in possibilities, typically strings.
n, cutoffn is the maximum number of matches to return and must be greater than 0. cutoff is a float in [0, 1]; the default is 0.6.

Returns: ratio() returns a float in [0, 1]. get_close_matches returns a list of the best matches, most similar first.

  • The last two prints use two 206-element lists that share six letters and two hundred "x" tokens, but with the popular block on opposite ends. autojunk=True treats "x" as popular junk and the ratio drops sharply; autojunk=False keeps those matches.
  • This is not a visual or semantic text-diff test.
python
from difflib import SequenceMatcher, get_close_matches

print(SequenceMatcher(None, 'car', 'automobile').ratio())
print(SequenceMatcher(None, 'colour', 'color').ratio())
print(SequenceMatcher(None, 'abc', 'abc').ratio())
print(get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']))

a = ['x'] * 200 + list('abcdef')
b = list('abcdef') + ['x'] * 200
print(SequenceMatcher(None, a, b, autojunk=True).ratio())
print(SequenceMatcher(None, a, b, autojunk=False).ratio())

Expected output

0.15384615384615385
0.9090909090909091
1.0
['apple', 'ape']
0.02912621359223301
0.970873786407767

Related: Inline text diff tool, Code diff tool, str methods

Official documentation →

unified_diff and line terminators

unified_diff(a, b) compares two sequences of lines and yields a compact unified diff, with n context lines (default 3). fromfile and tofile fill the --- and +++ headers.

By default lineterm is "\n", so the control lines (---, +++, @@) are created with a trailing newline. That matches file.readlines() input and file.writelines() output. If your lines do not already include trailing newlines, those data lines are emitted without an extra terminator, and joining the iterator with an empty string can glue the first data lines together. For inputs without trailing newlines, pass lineterm="" so every yielded line is uniformly newline-free, then join with "\n" if you need a printable block.

unified_diff and the lineterm argument

difflib.unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')

Control lines get lineterm (default "\n"). For lines that already lack newlines, set lineterm="" so the output is uniformly newline-free.

ParameterDescription
a, bSequences of lines to compare.
fromfile, tofileLabels for the --- and +++ headers.
fromfiledate, tofiledateOptional timestamps included in the headers when provided.
nNumber of context lines. The default is 3; this example uses 1 to keep the output short.
linetermString appended to control lines. The default is a newline. Use an empty string when the input lines have no trailing newlines.

Returns: An iterator of diff lines. This example materializes the iterator with list().

  • The first joined block shows the default lineterm pitfall: " beta", "-gamma", and "+delta" have no newlines, so they run together after the @@ line.
  • This page does not apply a patch and does not read a user file.
python
from difflib import unified_diff

old = ['alpha', 'beta', 'gamma']
new = ['alpha', 'beta', 'delta']
default = list(unified_diff(old, new, fromfile='old.txt', tofile='new.txt', n=1))
empty = list(unified_diff(old, new, fromfile='old.txt', tofile='new.txt', n=1, lineterm=''))
print(default)
print(''.join(default))
print(empty)
print('\n'.join(empty))

Expected output

['--- old.txt\n', '+++ new.txt\n', '@@ -2,2 +2,2 @@\n', ' beta', '-gamma', '+delta']
--- old.txt
+++ new.txt
@@ -2,2 +2,2 @@
 beta-gamma+delta
['--- old.txt', '+++ new.txt', '@@ -2,2 +2,2 @@', ' beta', '-gamma', '+delta']
--- old.txt
+++ new.txt
@@ -2,2 +2,2 @@
 beta
-gamma
+delta

Related: Unified diff patch tool, Inline text diff tool

Official documentation →