Swiffy
Swiffy

Reputation: 4693

Python return which list items string contains

I have a list of words and a string like so:

wordlist = ['fox', 'over', 'lazy']
paragraph = 'A quick brown fox jumps over the lazy fox.'

I want to know which words in the list occur in the string and return them. Is there some relatively clever way to do this?

For example, any(word in paragraph for word in wordlist) only returns True or False, but not the actual words that were found.

Upvotes: 0

Views: 2551

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122152

Use your test in a list comprehension:

words_in_paragraph = [word for word in wordlist if word in paragraph]

This moved the test for the any() generator to the end.

Demo:

>>> wordlist = ['fox', 'over', 'lazy']
>>> paragraph = 'A quick brown fox jumps over the lazy fox.'
>>> [word for word in wordlist if word in paragraph]
['fox', 'over', 'lazy']
>>> another_wordlist = ['over', 'foo', 'quick']
>>> [word for word in another_wordlist if word in paragraph]
['over', 'quick']

Note that, just like your any() test, this'll work for partial word matches too, of course:

>>> partial_words = ['jump', 'own']
>>> [word for word in partial_words if word in paragraph]
['jump', 'own']

Upvotes: 4

hspandher
hspandher

Reputation: 16743

You can use filter

included_words = filter(lambda word: word in paragraph, wordlist)

Although in python3, this would generate an iterator, so if you want a list use list comprehension approach (or you can just call list on filter result if you prefer), otherwise iterator would do just fine.

included_words = list(filter(lambda word: word in paragraph, wordlist))

OR

included_words = [word for word in wordlist if word in paragraph]

Upvotes: 1

Related Questions