python3 如何匹配 == 多个字符串

标签 python python-3.x

我正在尝试使用 == 来匹配多个结果。

这是我有问题的线路:

if string1.lower().rstrip() == "remove from list" or "del from list":
    do something
else:
    do something else

我想精确匹配“从列表中删除”,或传递到不同的函数,或精确匹配“从列表中删除”或传递到不同的函数。

要添加到示例中,“传递给我提到的不同函数将是......”

if string1.lower().rstrip() == "从列表中删除我"或 "从列表中删除我"

所以精确匹配很重要,这就是为什么我使用 == 而不是像 'in' 这样的替代方法

我还希望能够扩展此处适用的任何方法,以便能够根据需要匹配 4、5、6 个字符串。

最佳答案

使用 in 与要匹配的字符串列表,如果该字符串等于列表中的字符串之一,则为 True:

if string1.lower().rstrip() in ["remove from list", "del from list"]:

或者使用 == 两次:

if string1.lower().rstrip() == "remove from list" or string1.lower().rstrip() == "del from list"]:

这个,string1.lower().rstrip() ==“从列表中删除”或“从列表中删除”,将始终评估为Trueelse 永远不会到达,因为非空字符串的 bool 值是 True,所以它相当于 string1.lower().rstrip() == "从列表中删除”或 True,它总是 True

关于python3 如何匹配 == 多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55198773/

相关文章:

python - 从键值对列表创建矩阵

python - 在 Django 应用程序中设计用于内部和远程使用的 API

python - Django 多数据库(完整性检查)

python - 如何使用 Python 在 AWS CDK 中构建 DHCPOptionsAssociation

python - 导入错误 : cannot import name Thread

Python 找不到模块 h2o

python - 识别文章中的实体

python - 如何使用过滤器获取python数据框列名

python - 运行者方法可以替代方法链吗?

python - 在字符串中寻找单个确切的单词