Python - getting just the difference between strings

Rekovni picture Rekovni · Sep 27, 2017 · Viewed 17.4k times · Source

What's the best way of getting just the difference from two multiline strings?

a = 'testing this is working \n testing this is working 1 \n'
b = 'testing this is working \n testing this is working 1 \n testing this is working 2'

diff = difflib.ndiff(a,b)
print ''.join(diff)

This produces:

  t  e  s  t  i  n  g     t  h  i  s     i  s     w  o  r  k  i  n  g     
     t  e  s  t  i  n  g     t  h  i  s     i  s     w  o  r  k  i  n  g     1     
+  + t+ e+ s+ t+ i+ n+ g+  + t+ h+ i+ s+  + i+ s+  + w+ o+ r+ k+ i+ n+ g+  + 2

What's the best way of getting exactly:

testing this is working 2?

Would regex be the solution here?

Answer

Kaushik NP picture Kaushik NP · Sep 27, 2017

The easiest Hack, credits @Chris, by using split().

Note : you need to determine which is the longer string, and use that for split.

if len(a)>len(b): 
   res=''.join(a.split(b))             #get diff
else: 
   res=''.join(b.split(a))             #get diff

print(res.strip())                     #remove whitespace on either sides

# driver values

IN : a = 'testing this is working \n testing this is working 1 \n' 
IN : b = 'testing this is working \n testing this is working 1 \n testing this is working 2'

OUT : testing this is working 2

EDIT : thanks to @ekhumoro for another hack using replace, with no need for any of the join computation required.

if len(a)>len(b): 
    res=a.replace(b,'')             #get diff
else: 
    res=b.replace(a,'')             #get diff