首页 > 解决方案 > 如何正确使用括号?

问题描述

为什么它的工作方式不同?

p='/content/Images_of_Waste/img/PET968.txt'
p[-3:]!='txt' and p[-3:]!='jpg'
False
p[-3:]!=('txt' and 'jpg')
True

如何正确使用括号?

标签: pythonstringboolean-expression

解决方案


在 Python 中,非空字符串实际上是True.

也就是说,

if 'txt':
    # this code will execute

然而,正如@gimix 下面提到的那样,

if 'txt' == True:
    # this code will not execute

('txt' and 'jpg'), 'txt'is notFalse和not 而言'jpg',因此,根据@Manish 的评论('txt' and 'jpg')进行评估。'jpg'


推荐阅读