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

标签 python string python-3.x

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

相关文章:

python - 如何获取特定类启动的事件线程数?

python - 使用 Google Data API 时 GAE 中的本地时区问题

c++ - 如何为 python 编译 C/C++ 函数

C++:字符串结构的相等性

string - 各种位串的模式搜索

python - django.core.exceptions.ImproperlyConfigured : uses parameter name 'order.id' which isn't a valid Python identifier

c - 如何检查字符串是否没有任何字母数字字符?

python-3.x - Jinja 找不到模板路径

Python Datacompy 库 : how to save report string into a csv file?

python - 删除 Pandas Dataframe 列范围内每列总和小于 10 的列