Skip to content

Instantly share code, notes, and snippets.

@fomightez
Forked from ines/diff_strings.py
Last active September 12, 2019 20:55
Embed
What would you like to do?
Print colored visual diff in Python - from Ines Montani https://twitter.com/_inesmontani/status/1156904128666316800
import difflib
from wasabi import color
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!"))
@fomightez
Copy link
Author

Use %pip install wasabi first if trying in a Jupyter notebook cell.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment