Python Diff Two Multiline Strings Like GitHub

Viewed 2834

I want to achieve a diff output like github's commit diff view. And I tried this:

import difflib

first = """
def
baz
"""

second = """
deff
ba
bar
foo
"""

diff = ''
for text in difflib.unified_diff(first, second):
    for prefix in ('---', '+++', '@@'):
        if text.startswith(prefix):
            break
    else:
        diff += text

The output is:

 d e f+f 
 b a-z 
+b+a+r+
+f+o+o+

How can I achieve,

1 def+f
2 ba-z
+
3 bar
4 foo
# -
# 5 line
# 6 line

an output just like this. Thanks.

1 Answers
Related