I'm trying to find a Python way to diff strings. I know about difflib
but I haven't been able to find an inline mode that does something similar to what this JS library does (insertions in green, deletions in red):
one_string = "beep boop"
other_string = "beep boob blah"
Is there a way to achieve this?
One possible way (see also @interjay's comment to the OP) is
import difflibred = lambda text: f"\033[38;2;255;0;0m{text}\033[38;2;255;255;255m"
green = lambda text: f"\033[38;2;0;255;0m{text}\033[38;2;255;255;255m"
blue = lambda text: f"\033[38;2;0;0;255m{text}\033[38;2;255;255;255m"
white = lambda text: f"\033[38;2;255;255;255m{text}\033[38;2;255;255;255m"def get_edits_string(old, new):result = ""codes = difflib.SequenceMatcher(a=old, b=new).get_opcodes()for code in codes:if code[0] == "equal": result += white(old[code[1]:code[2]])elif code[0] == "delete":result += red(old[code[1]:code[2]])elif code[0] == "insert":result += green(new[code[3]:code[4]])elif code[0] == "replace":result += (red(old[code[1]:code[2]]) + green(new[code[3]:code[4]]))return result
Which just depends just on difflib
, and can be tested with
one_string = "beep boop"
other_string = "beep boob blah"print(get_edits_string(one_string, other_string))