ndiff() method - Returning Differ Style Difference














































ndiff() method - Returning Differ Style Difference




ndiff()

ndiff():This is a fuction of difflib() module . It has the same functionality that is
available through
Differ Instance.

It takes in two list of strings a and b compares the two and returns a Differ-style delta
(a generator generating the delta lines). In other words it returns a generator
that has a list of lines showing the difference between two lists. It allows us
to compare a string character by character.

It also lets us specify linejunk and charjunk
Thus it takes in four parameters.

  • a & b:
    The two list od strings to be compared.
  • Linejunk: A function that accepts a single string argument, and returns true if the string
    is junk, or false if not. The default value is None.
  • Charjunk : A function that accepts a character (a string of length 1), and returns if the
    character is junk, or false if not. The default is module-level function
    IS_CHARACTER_JUNK(), which filters out whitespace characters (a blank or tab;
    it’s a bad idea to include newline in this!).

SYNTAX

ndiff(a,b,linejunk=None,charjunk=IS_CHARACTER_JUNK)


Lets Take an example

CODE:

import difflib
from difflib import ndiff

String1= [
'Moon\n', 'Sun\n', 'Jupyter\n','Earth\n']
String2=[
'Noon\n', 'Son\n', 'Jupiter\n','Earth\n']

Difference=ndiff(String1,String2,linejunk=
None)

print(
''.join(Difference), end="")

Thus in the above code we have taken two input strings. Then used the ndiff function for
making the comparison

OUTPUT:


The output shows the changes with ‘+’ and  ‘-‘ sign.
It also shows the letter that has been changed.
The ‘^’  indicators have been correctly added to the
letter that has been identified as differences. The last word Earth has no changes
at all so there is no indicator.



Comments