Python:string中不包含字符串
我正在寻找执行以下搜索的一行Python表达式:Python:string中不包含字符串,python,Python,我正在寻找执行以下搜索的一行Python表达式: targets = ['habble', 'norpouf', 'blantom'] entry = "Sorphie porre blantom nushblot" found=False for t in targets : if t in entry : found = True break print ("found" if found else "not found") 这样我们就可以写出
targets = ['habble', 'norpouf', 'blantom']
entry = "Sorphie porre blantom nushblot"
found=False
for t in targets :
if t in entry :
found = True
break
print ("found" if found else "not found")
这样我们就可以写出这样的东西:
print("found" if entry.contains(targets) else "not found")
您可以使用任何:
targets = ['habble', 'norpouf', 'blantom']
entry = "Sorphie porre blantom nushblot"
result = 'found' if any(i in entry for i in targets) else 'not found'
您可以使用任何:
targets = ['habble', 'norpouf', 'blantom']
entry = "Sorphie porre blantom nushblot"
result = 'found' if any(i in entry for i in targets) else 'not found'
一个问题是标点符号,例如:
>>> entry = "Sorphie porre blantom! nushblot"
>>> targets.intersection(entry.split())
set()
>>> entry = "Sorphie porre NOTblantom! nushblot"
>>> 'blantom' in entry
True
但这仍然有效:
>>> 'blantom' in "Sorphie porre blantom! nushblot"
True
你也可以用另一种方式来论证,说中的可能不是你真正想要的行为,例如:
>>> entry = "Sorphie porre blantom! nushblot"
>>> targets.intersection(entry.split())
set()
>>> entry = "Sorphie porre NOTblantom! nushblot"
>>> 'blantom' in entry
True
这取决于您的具体问题,但我认为@Ajax1234在这方面具有优势
一个问题是标点符号,例如:
>>> entry = "Sorphie porre blantom! nushblot"
>>> targets.intersection(entry.split())
set()
>>> entry = "Sorphie porre NOTblantom! nushblot"
>>> 'blantom' in entry
True
但这仍然有效:
>>> 'blantom' in "Sorphie porre blantom! nushblot"
True
你也可以用另一种方式来论证,说
中的可能不是你真正想要的行为,例如:
>>> entry = "Sorphie porre blantom! nushblot"
>>> targets.intersection(entry.split())
set()
>>> entry = "Sorphie porre NOTblantom! nushblot"
>>> 'blantom' in entry
True
这实际上取决于您的具体问题,但我认为@Ajax1234在这里有优势。将目标设置为一个集合不是更好吗?@delerious如果我们在目标中检查是否存在,最好将目标设置为一个集合,但是在这种情况下,我们只是在重复它。@Delirious莴苣请展示它将如何与一个集合一起使用。这听起来也不错。targets
成为一个集合不是更好吗?@Delrious莴苣如果我们在targets
中检查是否存在,那么最好将targets
作为一个集合,但是,在这种情况下,我们只是对它进行迭代。@Delrious莴苣请展示它如何处理集合。听起来也不错。最后使用entry.contains(targets)
的示例似乎代表了一个相反的问题(因为contains
的单词选择),尽管这似乎不是您的意思。无论如何,如果您想知道entry
是否包含所有targets
,您可以执行all(target in entry for targets in targets)
或类似于set(targets).issubset(entry.split())
的操作。最后使用entry.contains(targets)
的示例似乎代表了一个相反的问题(因为包含
单词选择),尽管这似乎不是你的意思。无论如何,如果你想知道条目
是否包含所有的目标
,你可以做全部(目标中的目标对应目标中的目标)
或者类似的设置(目标)。issubset(entry.split())
。