此代码将在使用 difflib 之前和之后进行比较,并打印差异,如果没有差异,我该如何打印差异?
import difflib
before = ['abc\n', 'def\n']
after = ['xyz\n', 'def\n']
for line in difflib.unified_diff(before, after):
print (line)
我试着把它写成:
import difflib
before = ['abc\n', 'def\n']
after = ['xyz\n', 'def\n']
for line in difflib.unified_diff(before, after):
x = len(line)
if x == 0:
print (line)
else:
print("no diff")
但它不起作用!
输入代码,打印出来
你只需要稍微重新安排一下你的逻辑。
试试这个,
import difflib
before = ['abc\n', 'def\n']
after = ['xyz\n', 'def\n']
diff = list(difflib.unified_diff(before, after))
if len(diff) == 0:
print("no diff")
else:
for line in diff:
print(line)
首先运行 difflib 函数并检查长度。如果为零,则不打印 diff,但如果不是,则照常运行 for 循环。
尝试使用 ndiff :https://docs.python.org/3/library/difflib.html#difflib.ndiff
你的解决方案很简单, 声明变量后,
diff = list(difflib.ndiff(before, after)
if not diff:
print("It doesn't exist")