Python - difference between two strings Python - difference between two strings python python

Python - difference between two strings


You can use ndiff in the difflib module to do this. It has all the information necessary to convert one string into another string.

A simple example:

import difflibcases=[('afrykanerskojęzyczny', 'afrykanerskojęzycznym'),       ('afrykanerskojęzyczni', 'nieafrykanerskojęzyczni'),       ('afrykanerskojęzycznym', 'afrykanerskojęzyczny'),       ('nieafrykanerskojęzyczni', 'afrykanerskojęzyczni'),       ('nieafrynerskojęzyczni', 'afrykanerskojzyczni'),       ('abcdefg','xac')] for a,b in cases:         print('{} => {}'.format(a,b))      for i,s in enumerate(difflib.ndiff(a, b)):        if s[0]==' ': continue        elif s[0]=='-':            print(u'Delete "{}" from position {}'.format(s[-1],i))        elif s[0]=='+':            print(u'Add "{}" to position {}'.format(s[-1],i))        print()      

prints:

afrykanerskojęzyczny => afrykanerskojęzycznymAdd "m" to position 20afrykanerskojęzyczni => nieafrykanerskojęzyczniAdd "n" to position 0Add "i" to position 1Add "e" to position 2afrykanerskojęzycznym => afrykanerskojęzycznyDelete "m" from position 20nieafrykanerskojęzyczni => afrykanerskojęzyczniDelete "n" from position 0Delete "i" from position 1Delete "e" from position 2nieafrynerskojęzyczni => afrykanerskojzyczniDelete "n" from position 0Delete "i" from position 1Delete "e" from position 2Add "k" to position 7Add "a" to position 8Delete "ę" from position 16abcdefg => xacAdd "x" to position 0Delete "b" from position 2Delete "d" from position 4Delete "e" from position 5Delete "f" from position 6Delete "g" from position 7


I like the ndiff answer, but if you want to spit it all into a list of only the changes, you could do something like:

import difflibcase_a = 'afrykbnerskojęzyczny'case_b = 'afrykanerskojęzycznym'output_list = [li for li in difflib.ndiff(case_a, case_b) if li[0] != ' ']


You can look into the regex module (the fuzzy section). I don't know if you can get the actual differences, but at least you can specify allowed number of different types of changes like insert, delete, and substitutions:

import regexsequence = 'afrykanerskojezyczny'queries = [ 'afrykanerskojezycznym', 'afrykanerskojezyczni',             'nieafrykanerskojezyczni' ]for q in queries:    m = regex.search(r'(%s){e<=2}'%q, sequence)    print 'match' if m else 'nomatch'