【问题标题】:if (string or string or string) not in variable [duplicate]如果(字符串或字符串或字符串)不在变量中[重复]
【发布时间】:2016-05-01 04:35:00
【问题描述】:

我正在尝试使if 语句起作用,但由于某些原因它不起作用。应该很简单。

假设字符串title = "Today I went to the sea"

我的代码是:

 if "Today" or "sea" in title:
      print 1

 if "Today" or "sea" not in title:
      print 1

两种规格的结果都是 1。

【问题讨论】:

    标签: python python-2.7 if-statement


    【解决方案1】:

    将您的代码更改为:

    if "Today" in title or "sea" in title:
      print 1
    

    (类似于第二段代码)。

    if 语句的工作原理是它们评估由 orand 等单词连接的表达式。所以你的陈述是这样写的:

    if ("Today") or ("sea" in title):
      print 1
    

    因为 "Today"truthy 它总是评估为 true

    【讨论】:

    • 为什么投反对票?
    【解决方案2】:

    我保证这个问题已经在 SO 的其他地方得到解答,您应该在提出新问题之前先检查那里。

    你的代码有问题:

    if 'Today' or 'sea' in title:
    

    这会检查 'today' 是否为 True 或 'sea' 是否在标题中,'today' == type(string) 因此它存在/True,'sea' in title == True 并评估为 True,@987654322 @ 'today' 再次是类型(字符串),因此存在 / True 和 'sea' 不在 title = False 中,并且再次评估为 True。如何解决这个问题! if 'Today' in title or 'Sea' in title: 或以下使其易于修改!祝你好运!

    strings_to_compare = ['Today', 'sea', 'etc...']
    
    for i in strings_to_compare:
        if i in title:
            print i
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多