python - 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 中有一个名为椰子的项目时,我只得到椰子的打印,而不是坚果的打印?
我将永远感激任何帮助。
解决方案
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")
推荐阅读
- php - Get_Header 在主页 Wordpress 上不起作用 - 几乎所有东西都试过了
- r - R中多列的条件均值?
- google-tag-manager - 通过 Google 跟踪代码管理器跟踪 Pardot 表单提交
- python - 从 python 中的 factor_analysisr 计算拟合优度和 rmsea
- php - 异常“无法在 BinaryFileResponse 实例上设置内容。” 仅在生产服务器上抛出
- php - 我在解析 php sdk 时遇到问题
- r - GGtext 跟随 group_split 和 map
- pyspark - 如何计算 PySpark 数据框列中字符串的出现次数?
- python - Visual Studio Code 没有为 numpy 正确实现 IntelliSense,但适用于所有其他模块 [内部图片]
- dll - 如何导入两个同名的 DLL(x86 和 x64)?