1

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")
1
  • The example at the end using entry.contains(targets) seems to represent an opposite problem (because of the contains word choice), though it seems that's not what you meant. Anyhow, if you want to find out if entry contains all of targets, you can either do all(target in entry for target in targets) or something like set(targets).issubset(entry.split()). Commented Feb 21, 2018 at 4:36

2 Answers 2

5

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'
Sign up to request clarification or add additional context in comments.

3 Comments

Wouldn't it be better for targets to be a set?
@DeliriousLettuce It would be best for targets to be a set if we were checking for existence in targets, however, in this case, we are merely iterating over it.
@DeliriousLettuce Please show how it would play with a set. That sounds good too.
2
>>> 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.