我有两个字符串s和s2
s = "catwalksonterrace9_ontheweekend_at7am"
s2= "catwalksonterrace$no_ontheweekend_at.*"
我需要比较两个字符串并提取不匹配的部分
Python中两个字符串中的
$no = 9
和.* = 7am
。我是python的新手,我将如何实现呢? 最佳答案
看一下difflib,它很棒,可以完全按照您想要的去做:)
https://docs.python.org/2/library/difflib.html
import difflib
d = difflib.Differ()
diffs = []
in_diff = False
for c in d.compare(s, s2):
if not in_diff and (c.startswith("+") or c.startswith("-")):
diffs.append(["", ""])
in_diff = True
if c.startswith("+"):
diffs[-1][0] += c.replace("+ ", "")
elif c.startswith("-"):
diffs[-1][1] += c.replace("- ", "")
else:
in_diff = False
print(diffs)
这将创建一个列表列表,其中每个子列表的第一个值在第1行为diff,第二个值在第2行为diff
输出将是:
[['$no', '9'], ['.*', '7am']]
然后,您可以循环浏览,按要求打印:
for diff in diffs:
print(diff[0], "=", diff[1])