Reputation: 11
I created a small program that searches for a specific word in a list. It seems to work, but I'd like it to also print out the word that it found.
So far I have this, but it only returns the first word from the list, even if it isn't the word that it found.
some advice to make this work would be appreciated. Thanks,
text = 'this is a test'
words =['image', 'is']
if any(k in text for k in words):
for k in words:
print (k)
print ("word found")
break
else:
print ("nope")
Upvotes: 0
Views: 185
Reputation: 88305
Note that in the loop for k in words
you are simply printing all words, without checking if they are actually contained in text
. You also need to split
the elements in text
to check if the resulting list contains k
.
You want to do something like:
for k in words:
if k in text.split():
print (k)
print ("word found")
Output
is
word found
The same applies to the initial condition, if you want to initially check if any words are contained in text
, you need to split the words:
any(k in text.split() for k in words)
However, note that, as posted by @Austin, the most suited tool for what you're trying to do are sets
. You can easily compute the common elements on both sets by computing the intersection as:
set(text.split()) & set(words)
# {'is'}
Find more about the topic in sets — Unordered collections of unique elements
Upvotes: 1
Reputation: 1592
Try this:
text = 'this is a test'
words =['image', 'is']
found = False
found_words = []
for k in words:
if k in text:
found_words.append(k)
found = True
if found:
print("words found:", found_words)
else:
print("nope")
Will print:
words found: ['is']
Upvotes: 0
Reputation: 9529
Try this:
text = 'this is a test'
words =['image', 'is']
for k in [w for w in words if w in text]:
print (k)
print ("word found")
Upvotes: 0
Reputation: 26037
If you are to find common elements, I would suggest to use a set
:
text = 'this is a test'
words = ['image', 'is']
print(set(words).intersection(text.split()))
# {'is'}
Upvotes: 0
Reputation: 554
Maybe restructure like this
text = 'this is a test'
words =['image', 'is']
words_found = [word for word in words if word in text]
if len(words_found)>0:
print(words_found)
else:
print("nope")
```
Upvotes: 0
Reputation: 18259
You just need to do this (one variation among many):
print(", ".join(k for k in words if k in text))
Upvotes: 1