首页 > 解决方案 > 与另一个字符串进行比较时,如何从 Python 中的字符串中提取唯一的子字符串?

问题描述

我有两个字符串,说'a'和'b'。我想比较'a'和'b'并只提取'a'的独特部分。我可以简单地检查“b”是否在 a 中并提取。但这里的问题是,字符串 'a' 或 'b' 随机忽略了空格,因此有点困难。

这是我到目前为止所做的

a = "catsand dogs some other strings"
b = "cats and dogs"

a_no_space = a.replace(" ", "")
b_no_space = b.replace(" ", "")
if(b_no_space in a_no_space and len(a_no_space) > len(b_no_space)):
  unique = a[b_no_space.index(b_no_space)+len(b_no_space):]

使用此解决方案,我得到以下结果

s some other strings

一开始我不想要那个's'。如何在 python 中解决这个问题?在这里使用正则表达式有帮助吗?如果有怎么办?

标签: pythonstringduplicates

解决方案


这是一个根据子字符串的字母逐步分割较大字符串的解决方案:

idx = 0
if len(a) > len(b):
    for letter in b:
        if letter in a and letter != " ":
            a= a[a.index(letter) + 1:]
    print(a)
else:
    for letter in a:
        if letter in b and letter != " ":
            b= b[b.index(letter) + 1:]
    print(b)

推荐阅读