Search code examples
pythonfor-looppraw

Filter strings in a for loop by list of words for reddit bot


So I'm trying to write a reddit bot to find articles with certain words in the title. Here's what I have so far:

top_posts = page.hot(limit=20)
for post in top_posts:
    title = post.title
    if title.lower() in ['word1',  'word2', 'word3']:
        print(title)

If I replace the last 2 lines with...

    if 'word1' in title.lower():
        print(title)

then it'll print the titles that have word1 in them but when I put it into a list it won't. I want to use a list to match different spellings of the same word. What am I doing wrong here?


Solution

  • You have the order of the operands wrongly placed and you're not doing it right.

    Use any to check if any of words in the list is contained in the title:

    if any(wd in title.lower() for wd in ['word1',  'word2', 'word3']):
        print(title)
    

    To check if all of the words are contained in title, use all instead.