Python Glossary Русский

all Python 3difflibterm

difflib

module

Comparing sequences: differences between texts in diff format, the similarity ratio of strings and finding close words.

Syntax

import difflib

difflib is for showing how two texts differ (unified_diff, ndiff) or for finding similar items: get_close_matches suggests "did you mean...". Its similarity measure is not Levenshtein distance but the share of matching blocks found by SequenceMatcher. The diff functions take lists of lines, not one string: split the text with splitlines(keepends=True) first, or the comparison runs character by character.

Examples

import difflib
print(difflib.get_close_matches('pyhton', ['python', 'java', 'perl']))  # → ['python']
a, b = ['one', 'two'], ['one', 'three']
print(list(difflib.unified_diff(a, b, lineterm=''))[2:])  # → ['@@ -1,2 +1,2 @@', ' one', '-two', '+three']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy