2012-06-12 83 views
0

我有IF語句;'str'和'str'的不支持的操作數類型。 Python

if contactstring == "['Practice Address Not Available']" | contactstring == "['']": 

我不知道是怎麼回事錯(可能是「」「S?),但我不斷收到在標題中提到的錯誤。

我已經看過其他問題的答案,但他們似乎都是關於使用數學運算的字符串,這不是這裏的情況。我知道這個問題是一種懶惰的,但我已經一整天的編碼,我筋疲力盡,我只是想迅速得到這個結束了。(Python的福利局)

+3

您可以使用'或'關鍵字代替'|'字符 – avasal

回答

11

|是Python中的按位或操作,並具有優先級,使Python解析此爲:

if contactstring == (""['Practice Address Not Available']"" | contactstring) == "['']": 

產生你看到的錯誤。

看來你想要的是一個邏輯或運營商,這是在Python拼寫「或」:

if contactstring == ""['Practice Address Not Available']"" or contactstring == "['']": 

會做你的期望。但是,因爲你對值的範圍比較相同的變量,這是更好的:

if contactstring in ("['Practice Address Not Available']", ['']): 
+0

+1來解釋優先級。 – 2012-06-12 04:32:07

3

|按位operator其沒有按't在字符串上工作...

使用or(布爾邏輯運算符)將產生更好的結果。

2

這裏的問題是按位或操作|。在通常工作正常的布爾環境中,但|優先於==,所以Python首先嚐試評估"['Practice Address Not Available']" | contactstring。這兩個操作數都是字符串,並且不能按位或兩個字符串。使用更正確的or可避免此問題,因爲它的優先級低於==

+0

+1來解釋優先級。 – 2012-06-12 04:31:52

相關問題