如何检查子字符串是否包含 "apple" 中的所有字母

How to check if a substring contains all of the letters in "apple"

如果我有字符串 "axplpett" 我想 return 为真,因为它的一个子字符串 "axplpe" 包含苹果的所有字母。

本来想用set方法,但是apple有重复字符

r = 'aapple'
w = list('axplpett')
try:
    for x in r:
        w.pop(w.index(x))
    print(True) # return True
except ValueError:
    print(False) # return False

就这么简单?

string = "axplpett"
test = "apple"
all(string.count(l) >= test.count(l) for l in test)

也许是这样:-

def findsub (sub,main):
    l1 = [i for i in sub]
    l2 = [i for i in main]
    for item in l1:
        if item in l2:
            l2.remove(item)
        else:
            return False
    return True
print(findsub('apple','appleccssfftt'))

您可以使用 Counter 轻松做到这一点。

我们从测试字符串'axplpett'中的字母数中减去目标字符串'apple'中的字母数。目标字符串中不在测试字符串中的任何字母都会导致这些字母的负计数。然后我们否定该结果,去除正数或零计数,如果目标字符串包含在测试字符串中,则结果计数器将为空。

from collections import Counter

target = 'apple'
test = 'axplpett'
counts = Counter(test)
counts.subtract(target)
print(not -counts)

counts = Counter('axplett')
counts.subtract(target)
print(not -counts)

输出

True
False