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.

1
  • 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]. Commented May 7, 2021 at 23:29

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Did not answer "why am I getting the "else" solution?".
thanks for that, @Enzo
Your explanation is not quite right. eggs[k] in spam[i] == True means eggs[k] in spam[i] and spam[i] == True because of operator chaining.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.