【发布时间】:2021-12-23 11:19:47
【问题描述】:
据我了解,and 是一个短路运算符,如doc 中所述。但是,为什么每次我运行下面的代码都会打印 c 部分?
我的解决方案:if ('RB' in t) and (not ',' in t): ...,但我想要的是一个解释。
test = '977'
if 'RB' and '+' in test:
print('a')
test = int(test.replace('RB+', '')) * 1000
elif ',' and 'RB' in test:
print('b')
temp_test = test.replace(',', '')
test = int(temp_test.replace('RB', '')) * 1000
elif 'RB' and not ',' in test:
print('c')
test = int(test.replace('RB', '')) * 1000
else:
test = int(test)
print(test)
输出
c
977000
【问题讨论】:
-
解析为
if 'RB' and (not ',' in test): -
“为什么每次我运行下面的代码都会打印 c 部分?”。因为
test中没有逗号。 -
您的所有条件都有效地忽略了
'RB',因为这本身就是真实的。if 'RB' and '+' in test:等价于if '+' in test: -
例如,在你的第一个
if中,'RB'的表达式本身就是truthy,所以可以重写为:if True and '+' in test:,所以True and可以去掉,留给你if '+' in test:。
标签: python python-3.x boolean