我一直在通过Python工作,但似乎无法通过字符串比较。我写了一个函数,它接受用户输入并对其进行评估。用户输入只能是“a”或“b”,否则会发生错误。我一直用这个:python中的字符串比较
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
然而,当我输入a
或b
,我收到这个:TypeError: unsupported operand type(s) for |: 'str' and 'str'
这是不正确的方法来比较字符串?有没有一个内置函数可以像Java一样执行此操作?谢谢!
“if”对应于你的'elif'在哪里? – ThiefMaster 2012-07-16 17:00:19
我把它剪掉以减少一些不必要的代码,但我会修复......谢谢! – 2012-07-16 17:01:37
除了以下答案中的关于运算符的要点之外,您还可以链接字符串方法,因此('a','b')'中的return resp.strip()。lower()可以是整个函数。 – geoffspear 2012-07-16 17:23:17