Reputation: 3362
I have the following set-up:
stuff = ['apple', 'I like apples today', 'orange', 'oranges and apples guys']
What I want to do: I want to search each value in a list to see if the word "orange" is contained anywhere within that lists index value.
In other words, my expected output is this:
orange
oranges and apples guys
What I am currently getting back is nothing.
Here is what I am currently doing:
for x in range(0, len(stuff), 1):
if 'orange' in stuff[x] == True:
print('testing to see if this works')
I am not successful with this, any suggestions?
Edit #1:
I tried searching for the contains
syntax to use with the re
module, but did not return anything useful.
Edit #2:
What about for cases like this:
stuff = ['crabapple']
'apple' in stuff
False
The word "apple" does exist, it's just part of another word. In this case, I'd like to return that as well.
Upvotes: 1
Views: 133
Reputation: 111
Use list comprehension
print ([x for x in stuff if "orange" in x])
Upvotes: 3
Reputation: 393
The find
method of strings returns the index of the substring, or -1 if not found:
for s in stuff:
if s.find('orange') != -1:
print(s)
Upvotes: 0
Reputation: 51
use this:
for x in range(0, len(stuff), 1):
if ('orange' in stuff[x])== True:
print('testing to see if this works')
for your code, python will judge 'stuff[x] == True' (and it will be False) then judge 'orange in False' so it will always be False.
Upvotes: 0
Reputation: 26
The way you use in is not correct, you should remove ==True
, or python will treat it as 'orange' in a binary list.
for x in stuff:
if 'orange' in x:
print('testing to see if this works\n')
print(x)
testing to see if this works
orange
testing to see if this works
oranges and apples guys
Upvotes: 0