【问题标题】:Why 'and not' gets executed in this if statement? [duplicate]为什么在这个 if 语句中执行“and not”? [复制]
【发布时间】: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


【解决方案1】:

因为您正在有效地检查字符串“RB”的“真实性”,即True。看: https://stackoverflow.com/questions/18491777/truth-value-of-a-string-in-python#:~:text=3%20Answers&text=Python%20will%20do%20its%20best,empty%20string%20is%20considered%20True%20.

您的第三个 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)

【讨论】:

    猜你喜欢
    • 2019-11-06
    • 2021-01-14
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 2019-07-07
    • 2017-01-26
    相关资源
    最近更新 更多