How to understand/use the Python difflib output?
<p>I am trying to make comprehensive diff that compares command line output of two programs. I used <code>difflib</code> and came up with this code:</p>

<pre><code>from difflib import Differ
from pprint import pprint
import sys

def readable_whitespace(line):
    return line.replace("\n", "\\n")

# Two strings are expected as input
def print_diff(text1, text2):
    d = Differ()
    text1 = text1.splitlines(True)
    text2 = text2.splitlines(True)

    text1 = [readable_whitespace(line) for line in text1]
    text1 = [readable_whitespace(line) for line in text2]

    result = list(d.compare(text1, text2))
    sys.stdout.writelines(result)
    sys.stdout.write("\n")
</code></pre>

<p>Some requirements I have:</p>

<ul>
<li>(obvious) It should be clear what is from which output when there is a difference</li>
<li>New lines are replaced with <code>\n</code> because they matter in my case and must be clearly visible when causing conflict</li>
</ul>

<p>I made a simple test for my diff function:</p>

<pre><code>A = "AAABAAA\n"
A += "BBB\n"
B = "AAAAAAA\n"
B += "\n"
B += "BBB"
print_diff(A,B)
</code></pre>

<p>For your convenience, here is test merged with the function so that you can execute it as file: <a href="http://pastebin.com/BvQw9naa" rel="nofollow">http://pastebin.com/BvQw9naa</a></p>

<p>I have no idea what is this output trying to say to me:</p>

<pre><code>- AAAAAAA\n?        ^^
+ AAAAAAA
?        ^
- \n+
  BBB
</code></pre>

<p>Notice those two <code>^</code> symbols on first line? What are they pointing to...? Also, I intentionally put trailing new line into one test string. I don't think the diff noticed that.</p>

<p>How to make the output comprehensive <strong>or</strong> learn to understand it?</p>

<p>The main problem with your example is how you are handling endline characters. If you completely replace them in the input, the output will no longer line up correctly, and so won't make any sense. To fix that, the <code>readable_whitespace</code> function should look something like this:</p>

<pre><code>def readable_whitespace(line):
    end = len(line.rstrip('\r\n'))
    return line[:end] + repr(line[end:])[1:-1] + '\n'
</code></pre>

<p>This will handle all types of endline sequence, and ensures that the lines are displayed correctly when printed.</p>

<p>The other minor problem is due to a typo:</p>

<pre><code>text1 = [readable_whitespace(line) for line in text1]
text1 = [readable_whitespace(line) for line in text2]
# --^ oops!    
</code></pre>

<p>Once these fixes are made, the output will look like this:</p>

<pre><code>- AAABAAA\n
?    ^
+ AAAAAAA\n
?    ^
+ \n
- BBB\n
?    --
+ BBB
</code></pre>

<p>which should hopefully now make sense to you.</p>

python python-2.7 difflib