Print colored visual diff in Python - from Ines Montani https://twitter.com/_inesmontani/status/1156904128666316800
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use
%pip install wasabi
first if trying in a Jupyter notebook cell.