Python String Diffs

March 17, 2012

One of my websites provides users with the ability to put up a textual profile, and they can edit it at any time. I wanted an easy way to see what changes had been made.

The source strings are paragraph based - a carriage return is only at the end of each paragraph - so it was difficult to use a raw difflib.Differ to work with the strings, because the lines could be very long.

Python also includes functionality to wrap text to column 80, I was able to combine this with the difflib functionality to do what I needed:

lOldProfile = textwrap.wrap(pThingOld.profile, 80)
lNewProfile = textwrap.wrap(pThingNew.profile, 80)

lDiff = difflib.Differ()
lProfileDiffLines = lDiff.compare(lOldProfile, lNewProfile)
lProfileDiff = '\n'.join(list(lProfileDiffLines))

References

Tags: diff textwrap python