python - 我们可以检查 python 中的 string 中是否有两个或多个子字符串

标签 python string if-statement substring

我正在尝试制作一个程序,可以使用 python 检查两个或多个子字符串是否在 1 个字符串中,你能告诉我如何做到这一点

str = "I like apple do you like apples?"

if 'apples' or 'like' in str:
    print('yes, I like apples')

最佳答案

实现这一点的方法是:

if 'apples' in str or 'like' in str:
    print('yes, I like apples')

这样做的原因是 or 运算符会将 if 语句划分为多个部分,因此对于您的原始版本:

if 'apples' or 'like' in str

你本质上是在问:

if 'apples'
or
if 'like' in str

并且因为如果您有任何带有简单字符串的 if 语句,则该字符串将等于 true,因此您要询问 if true or if 'like' in str 并且因为 true 始终为 true 即使两个子字符串都不在您正在搜索的字符串。

关于python - 我们可以检查 python 中的 string 中是否有两个或多个子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57024317/

相关文章:

python - 串口/dev/ttyS0和ttys*输入输出错误

c++ - 在 C++ 中复制后无法打印字符串值

C# string.Format 抛出异常

mysql - 当 IF 为真时选择列

c# - 嵌套 'if' -'else' 语句

performance - 如果/否则性能

python - 在 python 中更新 json 字典时出现奇怪的输出

python - 在 Keras 中下载 ResNet50 生成 "SSL: CERTIFICATE_VERIFY_FAILED"

python - numpy 将数组元素转换为频率的最快方法

在c中使用memcpy复制二进制数据