Home > other >  How to display differences between two strings with color etc like in diff format?
How to display differences between two strings with color etc like in diff format?

Time:10-10

I would like to display in some output the differences between two strings that makes it super easy for the user to understand. For example:

  1. SkyWalker
  2. kWalkerr

would output:

enter image description here

Is there a way to do that in Python, reusing some library? I checked out the difflib but didn't find how to achieve this.

CodePudding user response:

You can use the SequenceMatcher for this:

a = 'SkyWalker'
b = 'kWalkerr'

m = difflib.SequenceMatcher(a=a, b=b)

for tag, i1, i2, j1, j2 in m.get_opcodes():
    if tag == 'replace':
        print(f'<del>{a[i1:i2]}</del>', end='')
        print(f'<ins>{b[j1:j2]}</ins>', end='')
    if tag == 'delete':
        print(f'<del>{a[i1:i2]}</del>', end='')
    if tag == 'insert':
        print(f'<ins>{b[j1:j2]}</ins>', end='')
    if tag == 'equal':
        print(f'{a[i1:i2]}', end='')

Result:

<del>S</del>k<del>y</del>Walker<ins>r</ins>

  • Related