如何以统一的diff格式打印两个多行字符串的比较? [英] How to print the comparison of two multiline strings in unified diff format?
本文介绍了如何以统一的diff格式打印两个多行字符串的比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您知道有什么库可以帮助您做到这一点吗?
Do you know any library that will help doing that?
我将编写一个函数,以统一的diff格式打印两个多行字符串之间的差异。像这样的东西:
I would write a function that prints the differences between two multiline strings in the unified diff format. Something like that:
def print_differences(string1, string2):
"""
Prints the comparison of string1 to string2 as unified diff format.
"""
???
使用示例如下:
string1="""
Usage: trash-empty [days]
Purge trashed files.
Options:
--version show program's version number and exit
-h, --help show this help message and exit
"""
string2="""
Usage: trash-empty [days]
Empty the trash can.
Options:
--version show program's version number and exit
-h, --help show this help message and exit
Report bugs to http://code.google.com/p/trash-cli/issues
"""
print_differences(string1, string2)
应该打印出以下内容:
--- string1
+++ string2
@@ -1,6 +1,6 @@
Usage: trash-empty [days]
-Purge trashed files.
+Empty the trash can.
Options:
--version show program's version number and exit
推荐答案
这是我的解决方法:
def _unidiff_output(expected, actual):
"""
Helper function. Returns a string containing the unified diff of two multiline strings.
"""
import difflib
expected=expected.splitlines(1)
actual=actual.splitlines(1)
diff=difflib.unified_diff(expected, actual)
return ''.join(diff)
这篇关于如何以统一的diff格式打印两个多行字符串的比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文