2012-07-16 101 views
2

我一直在通过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 

然而,当我输入ab,我收到这个:TypeError: unsupported operand type(s) for |: 'str' and 'str'

这是不正确的方法来比较字符串?有没有一个内置函数可以像Java一样执行此操作?谢谢!

+1

“if”对应于你的'elif'在哪里? – ThiefMaster 2012-07-16 17:00:19

+0

我把它剪掉以减少一些不必要的代码,但我会修复......谢谢! – 2012-07-16 17:01:37

+1

除了以下答案中的关于运算符的要点之外,您还可以链接字符串方法,因此('a','b')'中的return resp.strip()。lower()可以是整个函数。 – geoffspear 2012-07-16 17:23:17

回答

7

|是按位或运算符。你想要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"): 
5

你想要什么是respStr != 'a' and respStr != 'b'or是布尔歌剧tor,|这个按位数的 - 但是,你需要and为你的支票)。

但是你可以写的条件甚至更好的方式,而不需要重复的变量名:

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

这将返回True如果respStr是abFalse否则。