Python中assert能否判断字符串的in/not in?断言失败原因解析
问题:Python中
in操作符用于字符串包含检查时触发断言错误 我编写了一段代码,用于检查partialExpectedTitle是否包含在documentTitle中,但运行后触发了断言错误。我疑惑in和not in是否仅适用于列表?如何使其在字符串中生效?
代码示例
documentTitle = context.mailTrapPage.getExcelTitle().text.strip() excelTitle = download_path + "/" + documentTitle excelWorkbook = o.load_workbook(excelTitle) print("partialExpectedTitle is " + partialExpectedTitle) print("documentTitle is " + documentTitle) assert partialExpectedTitle in documentTitle is True
错误信息
assert partialExpectedTitle in documentTitle is True AssertionError Captured stdout: ['1 - AAAAAA qlgmdfol'] partialExpectedTitle is courses20220913_1110 documentTitle is courses20220913_111050.xlsx
解答
in和not in完全支持字符串类型,你的问题出在断言的写法上。
从输出能看到,partialExpectedTitle(courses20220913_1110)确实是documentTitle(courses20220913_111050.xlsx)的子串,但你的断言代码因运算优先级问题被错误解析了:
Python中比较运算符是链式的,partialExpectedTitle in documentTitle is True会被解析成partialExpectedTitle in documentTitle and documentTitle is True——显然documentTitle是字符串,不可能等于布尔值True,所以断言必然失败。
正确的写法有两种:
- 直接省略
is True,因为in本身返回布尔值,断言会自动校验:assert partialExpectedTitle in documentTitle - 用括号明确运算顺序:
assert (partialExpectedTitle in documentTitle) is True
验证一下:在Python交互环境中,"courses20220913_1110" in "courses20220913_111050.xlsx"返回True,所以逻辑本身没问题,只是断言写法错误导致了报错。
内容的提问来源于stack exchange,提问作者Faith Berroya
相关产品推荐
相关产品推荐

