首页 > 解决方案 > if item == "If" 和 if 'If' in item 的区别?

问题描述

我的代码在这里

        for index, item in enumerate(actdiagram, start=1):
          print(item+"&")
          # if item == "If":
          if 'If' in item:
             os.write(fd, ("if").encode('ascii'))
             indexOfIf = index

          elif index == (indexOfIf+1):
            os.write(fd, ("\"" + item + "\" then \n").encode('ascii'))

          else:
            os.write(fd, ("-->" + item + "\n").encode('ascii'))

我的问题是我的代码没有通过, if item == "If"但它工作正常,因为if 'If' in item: 我想知道为什么会这样。

标签: pythonpython-3.x

解决方案


==检查两件事是否相同,而 asin检查第二件事是否包含第一件事。

>>> "foo" in "blah blah foo blah blah"
True
>>> "foo" == "blah blah foo blah blah"
False

这里,foo是在第二个字符串中,但它还包含其他内容。

在您的情况下,它看起来item不是 string "If",但它确实包含它。


推荐阅读