Search code examples
pythontextcompare

(python) how to check changes between two strings like on e.g. text-compare.com


I have two texts and want to print the text that was added enter image description here i have two variables x and y which are a string. I would like it to look like this:

x = 'abcdefg'
y = 'abcdTHISefg'

print(TextCompare(x, y))

output:
> this

Solution

  • If you are interested in finding what has been added between two strings then it seems like Python's difflib might be of help.

    For example, the following gives this as an output on your test data:

    import difflib
    
    x = 'abcdefg'
    y = 'abcdTHISefg'
    
    diff = difflib.SequenceMatcher(None, x, y)
    
    for tag, x_start, x_end, y_start, y_end in diff.get_opcodes():
        if tag == 'insert':
            print(y[y_start:y_end].casefold())