Krithika Raghavendran
Krithika Raghavendran

Reputation: 457

Python String - Passing parameter to .__contains__ from a list

I have a list of strings like so:

filterlist = ["Apple", "Banana", "Cherry"]

I want to loop through this and check if any one of these strings is present as part of another string like

test_str = "An Apple a day keeps the Doctor away"

This is what I tried and succeeded:

for f in filterlist:
    if test_str.__contains__(f):
        doSomething()

But I tried doing the following and it didnt work:

if test_str.__contains__(f for f in filterlist):
    doSomething()

What is the difference between the first and second technique? What does f for f in filterlist do?

Upvotes: 0

Views: 179

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122007

What does f for f in filterlist do?

It's a generator expression, it creates a generator object:

>>> type(x for x in [])
<type 'generator'>

test_str.__contains__(f for f in filterlist) is literally checking whether that generator is in test_str*; which, given that you've only just created it, it's inevitably not going to be.

As Avinash has pointed out, using any is the correct way to convert your first code to a single line.

* note that foo.__contains__(bar) is usually written, more clearly, as bar in foo

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174696

Use any

Return True if any element of the iterable is true. If the iterable is empty, return False.

>>> test_str = "An Apple a day keeps the Doctor away"
>>> filterlist = ["Apple", "Banana", "Cherry"]
>>> any(i in test_str for i in filterlist)
True

Upvotes: 3

Related Questions