如何从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中修复这个问题?这里使用正则表达式有帮助吗?如果有,那是怎么回事?

您可以将搜索字符串转换为正则表达式,其中空格由's*'替换,该表达式将接受单词之间任意数量的中间空格(包括无空格):

a = "catsand dogs some other strings"
b = "cats and dogs"
import re
pattern = r"s*".join(map(re.escape,re.split("s+",b))) # r'catss*ands*dogs'
r = re.sub(pattern,"",a) # ' some other strings'

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

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)

相关内容

最新更新