Created
August 1, 2019 12:19
-
-
Save ines/04b47597eb9d011ade5e77a068389521 to your computer and use it in GitHub Desktop.
Print colored visual diff in Python
This file contains hidden or 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 | |
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
Same API as original post: