indianhearts indianhearts - 8 months ago 48
Python Question

if allwords in title: match

Using python3, i have a list of words like:

['foot', 'stool', 'carpet']

these lists vary in length from 1-6 or so. i have thousands and thousands of strings to check, and it is required to make sure that all three words are present in a title. where:
'carpet stand upon the stool of foot balls.'

is a correct match, as all the words are present here, even though they are out of order.

ive wondered about this for a long time, and the only thing i could think of was some sort of iteration like:

for word in list: if word in title: match!

but this give me results like
'carpet cleaner'
which is incorrect. i feel as though there is some sort of shortcut to do this, but i cant seem to figure it out without using excessive
list(), continue, break
or other methods/terminology that im not yet familiar with. etc etc.


You can use all():

words = ['foot', 'stool', 'carpet']
title = "carpet stand upon the stool of foot balls."

matches = all(word in title for word in words)

Or, inverse the logic with not any() and not in:

matches = not any(word not in title for word in words)