python中的字符串比较

2024-06-11 17:36:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在研究Python,但似乎无法通过字符串比较。我编写了一个接受用户输入并对其进行评估的函数。用户输入只能是“a”或“b”,否则将发生错误。我一直在用这个:

def checkResponse(resp):
    #Make the incoming string trimmed & lowercase
    respRaw = resp.strip()
    respStr = respRaw.lower()
    #Make sure only a or b were chosen
    if respStr != "a" | respStr != "b":
        return False
    else:
        return True

但是,当我输入ab时,我会收到这个:TypeError: unsupported operand type(s) for |: 'str' and 'str'

这是比较字符串的错误方法吗?是否有一个内置函数可以像使用Java那样执行此操作?谢谢!


Tags: the函数字符串用户stringmakereturndef
2条回答

您需要的是respStr != 'a' and respStr != 'b'or是布尔运算符,|是按位运算符-但是,您需要and进行检查)。

但是,您可以以更好的方式编写条件,而无需重复变量名:

return respStr in ('a', 'b')

如果respStr是abFalse,否则将返回True

|是按位或运算符。你想要or。(实际上您需要and。)

你写道:

if respStr != "a" | respStr != "b":

位运算符具有高优先级(类似于其他算术运算符),因此这相当于:

if respStr != ("a" | respStr) != "b":

其中两个!=操作是chained comparison operatorsx != y != z相当于x != y and y != z)。按位或对两个字符串应用是没有意义的。

你的意思是写:

if respStr != "a" and respStr != "b":

您还可以使用链式运算符编写:

if "a" != respStr != "b":

或者,使用包含运算符in

if respStr not in ("a", "b"):

相关问题 更多 >