如何正确使用括号?

How to use parentheses correctly?

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

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

如何正确使用括号?

if p[-3:] not in ('txt', 'jpg'):
    # Do stuff

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

也就是说,

if 'txt':
    # this code will execute

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

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

根据 ('txt' and 'jpg')'txt' 不是 False,也不是 'jpg',因此,('txt' and 'jpg') 计算为 'jpg'根据@Manish 的评论。

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

需要注意的重要一点:(来自docs

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

这里,p[-3:]给出txt。当你将它与p[-3:]!='txt' and p[-3:]!='jpg'进行比较时,第一个条件returns False as p[-3:]确实是txt。根据文档,如果 x 评估为 False,则其值为 returned。所以你得到 False


运算符优先级的另一点(来自docs
您可以在运算符优先级中看到首先评估以下内容:

Binding or parenthesized expression, list display, dictionary display, set display.

方括号中的表达式被赋予第一优先级并被首先计算。

p[-3:]!=('txt' and 'jpg')

在这种情况下,首先计算 ('txt' and 'jpg')python 中的任何 非空 字符串都具有真值 。所以第一个操作数的计算结果为 True,因为它有 3 个元素:t,x,t。回到 * if x 为 false 的那一行,它的值为 returned; ..., yis evaluated. Soy``` 是 png 这是一个 非空 字符串。

这个 python 将评估 las 操作数和 return 结果值,这里是 True.

当然 p[-3:]!=TrueTrueTrue 是 returned。

在第二部分,当您执行 ('txt' and 'jpg') 时,它的计算结果为 'jpg'

这么有效,你要做的是:

p[-3:] != 'jpg'

并且由于 p[-3:] 的计算结果为 'txt'

因此,

p[-3:] != ('txt' and 'jpg')

计算结果为真。

第一部分:

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

p[-3:]!='txt' return 对 p[-3:]!='jpg' return 假

因此, TrueFalse return 错误