Skip to content

Instantly share code, notes, and snippets.

@francbartoli
Forked from ines/diff_strings.py
Created August 1, 2019 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save francbartoli/a4a45573325ae027b82c265867649a58 to your computer and use it in GitHub Desktop.
Save francbartoli/a4a45573325ae027b82c265867649a58 to your computer and use it in GitHub Desktop.
Print colored visual diff in Python
import difflib
import wasabi
def diff_strings(a, b):
output = []
matcher = difflib.SequenceMatcher(None, a, b)
for opcode, a0, a1, b0, b1 in matcher.get_opcodes():
if opcode == "equal":
output.append(a[a0:a1])
elif opcode == "insert":
output.append(color(b[b0:b1], fg=16, bg="green"))
elif opcode == "delete":
output.append(color(a[a0:a1], fg=16, bg="red"))
elif opcode == "replace":
output.append(color(b[b0:b1], fg=16, bg="green"))
output.append(color(a[a0:a1], fg=16, bg="red"))
return "".join(output)
print(diff_strings("helloo world", "hello world!"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment