2012-07-16 48 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否則。