Python:string不包含字符串

2024-09-30 12:25:58 发布

您现在位置: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")

这样我们就可以写一些东西了,比如

^{pr2}$

Tags: infalseforif表达式entrytargets单行
2条回答
>>> targets = {'habble', 'norpouf', 'blantom'}
>>> entry
'Sorphie porre blantom nushblot'
>>> targets.intersection(entry.split())
{'blantom'}

一个问题是标点符号,例如:

^{pr2}$

但这仍然有效:

>>> 'blantom' in "Sorphie porre blantom! nushblot"
True

您也可以用另一种方式进行论证,并说in可能不是您实际想要的行为,例如:

>>> entry = "Sorphie porre NOTblantom! nushblot"
>>> 'blantom' in entry
True

这取决于您的特定问题,但我认为@Ajax1234在这里有优势。在

您可以使用any

targets = ['habble', 'norpouf', 'blantom']
entry = "Sorphie porre blantom nushblot"
result = 'found' if any(i in entry for i in targets) else 'not found'

相关问题 更多 >

    热门问题