Text Diff Checker — Developer Code Samples

Text diff algorithms compare two strings or files and highlight additions, deletions, and changes. Python's difflib generates unified and HTML diffs. The Unix diff command and Node's diff package provide similar functionality for CI pipelines and code review tools.

Try the interactive version online: Open Text Diff Checker Tool →

Parameters

Parameter Type Required Description
text1 str Yes Original text (left side / before)
text2 str Yes Modified text (right side / after)
diff_type str No Diff format: unified, context, html, sidebyside (default: unified)

Returns: Diff output as string with additions (+), deletions (-), and context lines

Code Examples

import difflib

# Unified diff (like git diff output)
text1 = """Line 1: Hello World
Line 2: This is unchanged
Line 3: This will be modified
Line 4: Goodbye World"""

text2 = """Line 1: Hello World
Line 2: This is unchanged
Line 3: This has been modified
Line 4: See you later"""

lines1 = text1.splitlines(keepends=True)
lines2 = text2.splitlines(keepends=True)

# Generate unified diff
diff = list(difflib.unified_diff(lines1, lines2, fromfile='original.txt', tofile='modified.txt'))
print(''.join(diff))

# Context diff (shows more surrounding context)
context_diff = list(difflib.context_diff(lines1, lines2, fromfile='original.txt', tofile='modified.txt'))
print(''.join(context_diff))

# HTML diff (colored output for web)
html_diff = difflib.HtmlDiff(wrapcolumn=80)
html_output = html_diff.make_file(lines1, lines2, fromdesc='Original', todesc='Modified')
with open('diff.html', 'w') as f:
    f.write(html_output)

# Simple line-by-line comparison
matcher = difflib.SequenceMatcher(None, lines1, lines2)
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
    if tag == 'equal':
        print(f"  {lines1[i1].rstrip()}")
    elif tag == 'replace':
        print(f"- {lines1[i1].rstrip()}")
        print(f"+ {lines2[j1].rstrip()}")
    elif tag == 'delete':
        print(f"- {lines1[i1].rstrip()}")
    elif tag == 'insert':
        print(f"+ {lines2[j1].rstrip()}")

# Similarity ratio (0.0 to 1.0)
ratio = difflib.SequenceMatcher(None, text1, text2).ratio()
print(f"Similarity: {ratio:.1%}")