def test_string_membership():
assert False == 'c' in 'apple'
assert True == 'a' in 'apple'
assert True == 'app' in 'apple'
p.s: - 我是python的初学者,无法找出错误。当我运行代码时,我的断言失败了。
答案 0 :(得分:5)
False == 'c' in 'apple'
不会被解释为
False == ('c' in 'apple')
但是,
(False == 'c') and ('c' in apple)
为了得到你想要的东西,请明确地加上括号。
False == ('c' in 'apple')
或更优选使用in
/ not in
:
def test_string_membership():
assert 'c' not in 'apple'
assert 'a' in 'apple'
assert 'app' in 'apple'
答案 1 :(得分:3)
比较链是一个问题,即处理的Python语法:
x < y < z
为:
x < y and y < z.
在您的情况下,这意味着表达式False == 'c' in 'apple'
被视为:
(False == 'c') and ('c' in 'apple')
这两个都是假的,因此导致断言。可以找到有关Python 3的比较链的详细信息here。
因此,避免这种情况的方法是使表达式显式化,例如:
assert False == ('c' in 'apple')
assert True == ('a' in 'apple')
assert True == ('app' in 'apple')
或者更好,因为与true/false
比较很少是一个好主意:
assert 'c' not in 'apple' # or "not('c' in 'apple')" if you're testing 'in'.
assert 'a' in 'apple'
assert 'app' in 'apple'
答案 2 :(得分:2)
与其他答案相反,此处发生的事情不是运算符优先级,而是comparison chaining。 a == b in c
表示(a == b) and (b in c)
,就像a < b < c
表示(a < b) and (b < c)
一样。但是,在任何一种情况下,结果都是相同的,这不是你想要做的。正如其他答案和评论中所指出的那样,可以通过使用括号来修复它,或者更好的是,通过不使用相等比较而只是执行assert 'c' not in 'apple'
。
您可以通过稍微不同的示例看到这是比较链接:
>>> 'a' == 'a' in 'ab'
True
无论优先级采用哪种方式,这显然都是错误的,但这是正确的,因为'a' == 'a'
和'a' in 'ab'
都是正确的。
答案 3 :(得分:1)
在这种情况下,您可以使用()
。有更好的方法来做你正在尝试的事情。
def test_string_membership():
assert False == ('c' in 'apple')
assert True == ('a' in 'apple')
assert True == ('app' in 'apple')
这是因为优先权。请在Python docs上了解详情。
in, not in, is, is not, <, <=, >, >=, <>, !=, ==
具有相同的优先级。所以Python会评估
False == 'c' in 'apple'
从左到右。
答案 4 :(得分:1)
使用括号应解决此问题,如
def test_string_membership():
assert False == ('c' in 'apple')
assert True == ('a' in 'apple')
assert True == ('app' in 'apple')