Stephen Boston
Stephen Boston

Reputation: 1189

Python : string contains NOT string in

I'm looking for a one-line Python expression that performs the following search :

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")

So that we can write something like this :

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

Upvotes: 1

Views: 266

Answers (2)

G_M
G_M

Reputation: 3372

>>> targets = {'habble', 'norpouf', 'blantom'}
>>> entry
'Sorphie porre blantom nushblot'
>>> targets.intersection(entry.split())
{'blantom'}

One problem would be punctuation though, for example:

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

But this would still work:

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

You could argue it the other way as well and say that in may not be the behaviour you actually want, for example:

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

It just really depends on your particular problem but I think @Ajax1234 has the advantage here.

Upvotes: 2

Ajax1234
Ajax1234

Reputation: 71451

You can use any:

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

Upvotes: 5

Related Questions