Reputation: 11
I want my program to return True if one word from a string is the same as a word in another string, but only when the whole word is matching and not single letters or parts. Here's an illustration on what I mean...
a = "hi please help"
b = "help anyone"
if any(a.split()) == any(b.split()):
print("True")
this works for the time being, but if I swap a for something else...
a = "h"
b = "help"
if any(a.split()) == any(b.split()):
print("True")
it still prints "True", which is not my intention. I did look at other similar threads to this, but I couldn't find any that solved the problem where parts are not accepted, but the whole string doesn't have to be a substring.
Upvotes: 1
Views: 689
Reputation: 24052
Try this:
set_a = set(a.split())
any(w in set_a for w in b.split())
This will evaluate to True
if any word w
from b.split()
is in set_a
, where set_a
is a set of words formed from a.split()
.
This should be faster than doing set intersection, since (1) it only creates a set for one of the split strings, (2) it stops searching as soon as a match is found, and (3) it doesn't create a set for the intersection result.
Upvotes: 1
Reputation: 1012
This should work: any([e in a.split() for e in b.split()])
Upvotes: 0
Reputation: 2569
Convert both strings to sets and create an intersection:
if set(a.split()) & set(b.split()):
print("True")
Upvotes: 1