everyday

Python - difflib Module

difflab is used for comparing text especially sequence of text using some common difference formats.

Differ class works on sequence of texts and produces default output similar to the diff tool available in Unix. It also provides change instructions along with human readable formats.

  • Lines prefixed with - were in the first sequence, but not the second.
  • Lines prefixed with + were in the second sequence, but not the first.
  • If a line has an incremental difference between versions, an extra line prefixed with ? is used to highlight the change within the new version.
import difflib


text1_lines= 'eaaasy peasy lemon2 squeesy'
text2_lines= 'easy peasye lemon1 squeesy'

d = difflib.Differ()
diff = d.compare(text1_lines.splitlines(),text2_lines.splitlines())
print('\n'.join(diff))
- eaaasy peasy lemon2 squeesy
?  --               ^
+ easy peasye lemon1 squeesy
?           +      ^

This is part of series of articles from Python Module of the Week

#pymotw

- 2 toasts