0

I am about to lose my mind. I'm fairly new to Python but I can usually brute force my way through. My code is never elegant, but I can usually solve whatever simple problems I have using what I learned from 'How to Automate the Boring Stuff with Python'.

Here's my problem:

I have a list of keywords and a list of strings. I want to search for each keyword in each of the strings. I want to return the whole string when a keyword is present in the string.

This is a boiled down version of what I'm trying to do:

spam = ['tyler is cool', 'lucy eats cool pasta']
eggs = ['tyler', 'pasta']

for i in range(len(spam)):
    for k in range(len(eggs)):
        print(eggs[k] in spam[i])
        if eggs[k] in spam[i] == True:
            print('please work')
        else:
            print('why doesn\'t this work')

My output looks like this:

True
why doesn't this work
False
why doesn't this work
False
why doesn't this work
True
why doesn't this work

If the statement is returning as True, why am I getting the "else" solution?

I've tried How to search for a keyword in a list of strings, and return that string? and Search a list of list of strings for a list of strings in python efficiently and it's not working. I'm stuck. Please help.

  • `eggs[k] in spam[i] == True` means `eggs[k] in spam[i] and spam[i] == True`. You should just have `if eggs[k] in spam[i]`. – khelwood May 07 '21 at 23:29

1 Answers1

2

Remove the == True

Use:

if eggs[k] in spam[i]

Edit:

You are getting the Else solution because using the expression you mentioned (if eggs[k] in spam[i] == True): you are checking if eggs[k] in spam[i] and spam[i] == True because of operator chaining

Also good to check this question about == vs is

khelwood
  • 55,782
  • 14
  • 81
  • 108
Christian H
  • 3,779
  • 2
  • 7
  • 17