![](/img/trans.png)
[英]How do I check if a string contains ALL letters of the alphabet in python?
[英]How to check if a substring contains all of the letters in “apple”
如果我有字符串“ axplpett”,我想返回true,因為它的“ axplpe”的子字符串包含了apple的所有字母。
我當時在考慮使用set方法,但是apple有重復的字符。
簡單嗎?
string = "axplpett"
test = "apple"
all(string.count(l) >= test.count(l) for l in test)
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
也許是這樣的:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.