首页 > 解决方案 > Python字符串搜索:如何找到完全匹配,而不是与其中包含搜索字符串的字符串匹配

问题描述

我需要我的脚本来显示不同单词的定义。

我正在使用循环来查找字符串 (X) 中的项目与数组之间的匹配项。

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")

问题是,当数组 X 中的项目是一个包含另一个单词的单词(例如椰子和坚果)时,两个打印都被执行。

我如何确保当数组 X 中有一个名为椰子的项目时,我只得到椰子的打印,而不是坚果的打印?

我将永远感激任何帮助。

标签: pythonloopssearchmatch

解决方案


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")

推荐阅读