【问题标题】:'and' operator in python3python3中的“和”运算符
【发布时间】:2020-04-20 16:29:16
【问题描述】:

我对编码很陌生,但我虽然了解“和”运算符的工作原理。在我提供的示例中,我会认为“假”语句会运行而不是“真”语句。有人能告诉我为什么这没有像我预期的那样表现吗?

string = 'asdf'

if 'z' and 's' in string:
    True
else:
    False

【问题讨论】:

  • 你想要'z' in string and 's' in string
  • 如果您有两个以上的字符,请使用列表理解:if all(c in string for c in 'zs'):
  • @Boris 我什至会为两个字符这样做以保留代码dry

标签: python-3.x expression comparison-operators


【解决方案1】:

and 关键字是表达式的一部分,它应该位于两个子表达式之间。在这里你写'z' and 's' in string 被解释为:

('z') and ('s' in string)

第一个子表达式 'z' 或多或少被评估为 True,而第二个子表达式更复杂一些(在您的示例中,它也被称为 True,因为 's' 实际上在string.

结合两个子表达式产生True(这里)。

你当然想写:

if 'z' in string and 's' in string:

【讨论】:

    【解决方案2】:

    只是为了建立上面的答案,要从 if 语句中获得您期望的正确输出,您需要指定 if "z" in string and "s" in string 以便 python 计算您打算执行的正确含义。

     string = 'asdf'
    
     if 'z' in string and 's' in string:
         print("True") 
     else:
         print("False")
    

    【讨论】:

      最近更新 更多