Overview
- The ndiff() function of Python difflib module returns a generator object containing differences between two lists of strings.
- Each difference is listed in the format <opcode, string>.
- When the opcode is '- ' the string is present only in the first list of strings and when it is '+ ' the string is present only in the second list of strings.
- If the opcode is ' ' there is no difference between the strings. The opcode '? ' represents the intra-line difference between two strings.
- The output of ndiff() is somewhat like the output of unified_diff() but more compact than that. There are no hunks and line numbers in the ndiff() output.
Example
# Example Python program that finds the difference
# between two lists of strings using the ndiff() function
# of difflib module
import difflib
# Create two lists of strings
textStrings1 = ["Hello", "World"]
textStrings2 = ["Hello", "Friends"]
# Find the differences
diffs = difflib.ndiff(textStrings1, textStrings2)
print(diffs)
print(type(diffs))
# Print each difference
for diff in diffs:
print(diff)Output
<generator object Differ.compare at 0x102f84cc0>
<class 'generator'>
Hello
- World
+ Friends