Python利用difflib比较字符串

简介:

#!/usr/bin/python
# -*- coding:utf-8 -*-

import difflib

file1 = file("my.txt","r")
file2 = file("new.txt","r")

temp1_context = file1.read()
temp2_context = file2.read()

file1_context = temp1_context.splitlines()
file2_context = temp2_context.splitlines()

diff = difflib.Differ().compare(file1_context,file2_context)

print "\n".join(list(diff))

------------------------------------------------

my.txt:

hack hack hack hack hack

new.txt:

h4ck h4ck h4ck h4ck h4ck

---------------------the result-----------------

- hack
?  ^

+ h4ck
?  ^

- hack
?  ^

+ h4ck
?  ^

- hack
?  ^

+ h4ck
?  ^

- hack
?  ^

+ h4ck
?  ^

- hack
?  ^

+ h4ck

















本文转sinojelly51CTO博客,原文链接:http://blog.51cto.com/pnig0s1992/396192,如需转载请自行联系原作者

相关文章
|
4月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
356 100
|
4月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
480 99
|
4月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
4月前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
4月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
4月前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
5月前
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
364 0
|
5月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
320 92
|
5月前
|
Python
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。

推荐镜像

更多