Skip to content

Instantly share code, notes, and snippets.

@rsbohn
Created October 21, 2011 20:24
Show Gist options
  • Save rsbohn/1304857 to your computer and use it in GitHub Desktop.
Save rsbohn/1304857 to your computer and use it in GitHub Desktop.
show differences in strings -- uses SequenceMatcher
from difflib import SequenceMatcher
def diff(actual, expected):
if actual != expected:
raise AssertionError(combine(actual, expected))
def combine(a,b):
"""Form one string showing the differences between a and b."""
sm = SequenceMatcher(None, a,b)
out = []
for op in sm.get_opcodes():
if op[0] == 'equal':
out.append(sm.a[op[1]:op[2]])
else:
out.append("("+sm.a[op[1]:op[2]]+"|"+sm.b[op[3]:op[4]]+")")
return ''.join(out)
aa="Beware the angry badger with a cudgel"
ab="Beware any badger with a stout cudgel"
# sample output:
# Beware (the |)an(gr|)y badger with a (|stout )cudgel
if __name__ == '__main__':
print combine(aa,ab)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment