简体   繁体   中英

Python string search: how to find exact matches, and not match with strings that contain searched string in them

I need my script to bring up definitions for different words.

I'm using a loop to look for matches between between an item in a string (X) and and array.

if any(i in X for i in ('coconut, Coconut')):
    print("found coconut")

if any(i in X for i in ('nut', 'Nut')):
    print("found nut")

The problem is, when the item in array X is a word containing another word (eg coconut & nut), both prints are executed.

How do I make sure that when there's an item called coconut in array X, I only get a print for coconut, and not for nut?

I'll be eternally grateful for any help.

You can test for equality of the individual strings, rather than the presence of a word in the X array (normally called a list in python, unless you are using numpy ):

if any(i == x for i in ('coconut', 'Coconut') for x in X):
    print("found coconut")

if any(i == x for i in ('nut', 'Nut') for x in X):
    print("found nut")

or better yet, you can convert the test string to lowercase first so that only a single for loop is necessary for each word:

if any(x.lower() == "coconut" for x in X):
    print("Found coconut")

This works unless you want to differentiate proper nouns, such as to propose a different definition for Jersey and jersey.

If X is a string, a simple equality check will work for this:

if X.lower() == "coconut":
    print("Found coconut")

This should work - i in X tests whether the substring i is found in the string X, while this tests whether they're equivalent.

if any(i == X for i in ('nut', 'Nut'):
    print('found nut')

you could trasnsform your string X into a set:

sx = set(X.split()) # to get the words you may use a regex, depending of how X looks
if sx & {'coconut, Coconut'}:
    print("found coconut")

Thanks everyone, I've figured it out.

In this case, it was enough simply to add a space before the shorter keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM