我有两个字符串 s 和 s2
s = "catwalksonterrace9_ontheweekend_at7am"
s2= "catwalksonterrace$no_ontheweekend_at.*"
我需要比较两个字符串并提取不匹配的部分
$no = 9
和 .* = 7am
来自 Python 中的两个字符串。我是 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])
关于python - 在python中提取不匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46876043/