Skip to content
Python Basics: Comparing Text with difflib

Python Basics: Comparing Text with difflib

October 12, 2026

A misspelled command or a changed settings line can be easier to handle with a small comparison tool. Python’s standard-library difflib module supplies suggestions, readable differences, and similarity scores.

Use Python 3.12 or newer in Bash on Linux. Each example runs independently with in-memory text; no data files are changed.

Suggest a command after a typo

Save as demo_difflib_1.py:

from difflib import get_close_matches

commands = ["start", "status", "stop"]
print(get_close_matches("statsu", commands, n=2, cutoff=0.6))
print(get_close_matches("xyz", commands, n=2, cutoff=0.6))

Run it from the directory where you saved it:

python3 demo_difflib_1.py

Output:

['status', 'start']
[]

n limits the number of suggestions. cutoff, from 0 to 1, sets the minimum similarity. Results put closer matches first; an empty list is normal. Offer suggestions for review rather than automatically running the nearest command.

Show changed lines

Save as demo_difflib_2.py:

from difflib import unified_diff

before = "color=blue\nsize=small\n".splitlines()
after = "color=green\nsize=small\n".splitlines()
changes = unified_diff(
    before, after, fromfile="before.ini", tofile="after.ini", lineterm=""
)
for line in changes:
    print(line)

Run it from the directory where you saved it:

python3 demo_difflib_2.py

Output:

--- before.ini
+++ after.ini
@@ -1,2 +1,2 @@
-color=blue
+color=green
 size=small

The headers label each version; @@ describes the affected line ranges. A minus marks removal, a plus marks addition, and a leading space marks unchanged context. The labels do not open files.

splitlines() removes line endings, so lineterm="" prevents extra newlines in the headers when using print(). This display compares line contents; it cannot reveal whether the final newline was added or removed.

Measure character similarity carefully

Save as demo_difflib_3.py:

from difflib import SequenceMatcher

matcher = SequenceMatcher(None, "color", "colour")
print(f"Similarity: {matcher.ratio():.2f}")
print(f"Empty strings: {SequenceMatcher(None, '', '').ratio():.2f}")
print(f"Different strings: {SequenceMatcher(None, 'cat', 'dog').ratio():.2f}")

Run it from the directory where you saved it:

python3 demo_difflib_3.py

Output:

Similarity: 0.91
Empty strings: 1.00
Different strings: 0.00

None supplies no custom rule for ignoring characters. ratio() ranges from 0 to 1; identical sequences score 1. The score measures matching content, not meaning or correctness, and swapping the inputs can change it. Use == when you need an exact equality check.

References

Acknowledgements

This post was created with assistance from AI.

Last updated on