Oscar W
Oscar W

Reputation: 484

Find occurences of any value in an array in a string and print it

I know this ones going to be something super simple, but it's just not working for me.

INDICATORS = ['dog', 'cat', 'bird']
STRING_1 = 'There was a tree with a bird in it'
STRING_2 = 'The dog was eating a bone'
STRING_3 = "Rick didn't let morty have a cat"


def FindIndicators(TEXT):
    if any(x in TEXT for x in INDICATORS):
        print x # 'x' being what I hoped was whatever the match would be (dog, cat)

Expected output:

FindIndicators(STRING_1)
# bird

FindIndicators(STRING_2)
# dog

FindIndicators(STRING_3)
# cat

Instead I'm getting an unsolved reference for 'x'. I have a feeling I'm going to face desk as soon as I see an answer.

Upvotes: 1

Views: 41

Answers (2)

Prune
Prune

Reputation: 77847

As described in the documentation, any returns a Boolean value, not a list of matches. All that call does is to indicate the presence of at least one "hit".

The variable x exists only within the generator expression; it's gone in the line after, so you can't print it.

INDICATORS = ['dog', 'cat', 'bird']
STRING_1 = 'There was a tree with a bird in it'
STRING_2 = 'The dog was eating a bone'
STRING_3 = "Rick didn't let morty have a cat"


def FindIndicators(TEXT):
    # This isn't the most Pythonic way,
    #   but it's near to your original intent
    hits = [x for x in TEXT.split() if x in INDICATORS]
    for x in hits:
        print x

print FindIndicators(STRING_1)
# bird

print FindIndicators(STRING_2)
# dog

print FindIndicators(STRING_3)
# cat

Upvotes: 2

Harvey
Harvey

Reputation: 5821

You're misunderstanding how any() works. It consumes whatever you give it and returns True or False. x doesn't exist after.

>>> INDICATORS = ['dog', 'cat', 'bird']
>>> TEXT = 'There was a tree with a bird in it'
>>> [x in TEXT for x in INDICATORS]
[False, False, True]
>>> any(x in TEXT for x in INDICATORS)
True

Instead do this:

>>> for x in INDICATORS:
...     if x in TEXT:
...         print x
...
bird

Upvotes: 3

Related Questions