为什么 'and not' 在这个 if 语句中被执行?

Why 'and not' gets executed in this if statement?

根据我的理解,anddoc 中解释的短路运算符。但是,为什么每次 运行 下面的代码都会打印 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

因为您正在有效地检查字符串 'RB 的 'truthiness',即 True。看: .

您的第三个 elif 分解为:

elif ('RB') and (not ',' in test'):

你可能想要:


if 'RB' in test and '+' in test:
    print('a')
    test = int(test.replace('RB+', '')) * 1000
elif ',' in test and 'RB' in test:
    print('b')
    temp_test = test.replace(',', '')
    test = int(temp_test.replace('RB', '')) * 1000
elif 'RB' in test and not ',' in test:
    print('c')
    test = int(test.replace('RB', '')) * 1000
else:
    test = int(test)

print(test)