簡體   English   中英

Python:字符串中包含NOT字符串

[英]Python : string contains NOT string in

我正在尋找執行以下搜索的單行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")

這樣我們就可以寫這樣的事情:

print("found" if entry.contains(targets) else "not found")

您可以使用any

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'
>>> targets.intersection(entry.split())
{'blantom'}

但是,一個問題是標點符號,例如:

>>> entry = "Sorphie porre blantom! nushblot"
>>> targets.intersection(entry.split())
set()

但這仍然有效:

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

你可以認為它的其他方式,以及和說, in可能不是你真正想要的行為,例如:

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

這實際上取決於您的特定問題,但我認為@ Ajax1234在這里有優勢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM