Python Glossary Русский

all Python 3difflibterm

difflib.Differ

diff formats

A class producing line-by-line differences in ndiff format; its compare(a, b) method returns a generator of lines.

Syntax

difflib.Differ(linejunk=None, charjunk=None).compare(a, b)

ndiff() is just Differ with another default: ndiff passes charjunk=IS_CHARACTER_JUNK, whereas Differ() treats nothing as junk by default. If your lines lack '\n' (say, from splitlines()), the '? ' hint lines still end in '\n', so joining everything with ''.join() scrambles the output.

Examples

import difflib
d = difflib.Differ()
print(list(d.compare(['a\n', 'b\n'], ['a\n', 'c\n'])))  # → ['  a\n', '- b\n', '+ c\n']
import difflib
out = list(difflib.Differ().compare(['a = 1', 'b = 2'], ['a = 1', 'b = 3']))
print(out[1:3])  # → ['- b = 2', '?     ^\n']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy