gpt4 book ai didi

python - 在python中提取不匹配的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 14:36:49 25 4
gpt4 key购买 nike

我有两个字符串 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com