Skip to main content
 首页 » 编程设计

python之我对 python 中的这段代码断言失败

2025年05月04日11java哥

def test_string_membership(): 
    assert False == 'c' in 'apple' 
    assert True == 'a' in 'apple' 
    assert True == 'app' in 'apple' 

p.s:- 我是 python 的初学者,无法找出问题所在。当我运行代码时,我的断言失败了。

请您参考如下方法:

False == 'c' in 'apple' 不被解释为

False == ('c' in 'apple') 

但是,

(False == 'c') and ('c' in apple) 

因为 comparison chaining .


为了得到你想要的,明确地加上括号。

False == ('c' in 'apple') 

或更优选地使用in/not in:

def test_string_membership(): 
    assert 'c' not in 'apple' 
    assert 'a' in 'apple' 
    assert 'app' in 'apple'