【问题标题】:Why doesn't != work for string index comparison?为什么 != 不能用于字符串索引比较?
【发布时间】:2023-02-01 16:56:02
【问题描述】:

我尝试使用输入“AC039”运行此代码

 code = input("Enter code: ").upper()
 if code[0] != ('N' or 'A' or 'C' ):
     print("The first character must be N, A or C")
else:
    print("Pass!")

它给了我输出错误结果:

The first character must be N, A or C

但是,如果我使用“not in”将“AC039”输入到下面的代码中,

code = input("Enter code: ").upper()
if code[0] not in ["N", "A", "C"]:
    print("The first character must be N, A or C")
else:
    print("Pass!")

结果输出是:

print("Pass!")

为什么“!=”不适用于第一组代码,因为 code[0] 和 'A' 都是字符串类型?

我在 code[0] 上使用 type 函数运行了一个检查,它返回了字符串类型。

code = input("Enter code: ").upper()
print(type(code[0]))
print(type('A'))

回报:

<class 'str'>
<class 'str'>

【问题讨论】:

  • code[0]'A' 可能是同一类型,但这并不意味着您正在应用的操作是正确的操作。
  • 如果变量 = ('N' 或 'A' 或 'C' ),则变量 == "N"。这是“或”运算符的属性。请记住,先执行括号中的某些代码。
  • @Kerighan 为什么 ('N' 或 'A' 或 'C') 只接受“N”?你能给我建议吗,因为我想我在某处误解了一个概念
  • 使用if code[0] not in ['N', 'A', 'C' ]:
  • 您期望('N' or 'A' or 'C') 评估什么?

标签: python string


【解决方案1】:

我认为这可以通过 a or b or c or ... 的粗略实现来最好地解释。

import typing as t


T = t.TypeVar("T")


def Or(*args: T) -> T:
    arg: T
    for arg in args[:-1]:
        if bool(arg) is True:
            return arg
    return args[-1]
>>> Or("N", "A", "T")  # equivalent to `"N" or "A" or "T"`
'N'
>>> Or("", None, 0)  # equivalent to `"" or None or 0`
0

【讨论】:

    【解决方案2】:

    这两行是相同的。

    if code[0] != ('N' or 'A' or 'C' ):
    
    if code[0] != 'N':
    

    因为 operator 'or' 检查第一个 operand 是否为真,所以它接受;否则,它会检查另一个。

    例子:

    >>> 1 or 2
    1
    >>> 0 or 3
    3
    >>> 0 or 2 or 3
    2
    >>> False or 2
    2
    >>> False or 0
    0
    

    因此,您可以应用此模式来解决您的问题。

    if code[0] in ('N', 'A', 'C'):
    

    或者

    if code[0] == 'N' or code[0] == 'A' or code[0] == 'C':
    

    【讨论】:

    • 我尝试了 if code[0] == 'N' or code[0] == 'A' or code[0] == 'C': 的方法,结果相同。但是如果我用它就可以了
    猜你喜欢
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 2012-02-09
    • 2017-10-28
    • 1970-01-01
    • 2011-06-09
    相关资源
    最近更新 更多