In python, create HTML by highlighting the differences of two simple lines

I need to highlight the differences between two simple lines using python, including the various substrings in the HTML span attribute. Therefore, I am looking for a simple way to implement the function shown in the following example:

hightlight_diff('Hello world','HeXXo world','red')

... it should return a string:

'He<span style="color:red">XX</span>o world'

I have googled and saw difflib, but it should be deprecated, and I did not find any good simple demo.

+5
source share
1 answer

All you need comes from difflib - for example:

>>> import difflib
>>> d = difflib.Differ()
>>> l = list(d.compare("hello", "heXXo"))
>>> l
['  h', '  e', '- l', '- l', '+ X', '+ X', '  o']

Each item in this list is a character from your two input lines, prefixed with one of

  • " " (2 spaces), the character present in this position on both lines
  • "- " (space), the character present in this position in the first line
  • "+ " ( ), .

, , .

, difflib docs.

+7

All Articles