2016-05-01 76 views
0

我試圖讓if語句正常工作,但由於某些原因,它不起作用。它應該非常簡單。如果(字符串或字符串或字符串)不在變量

假設字符串title = "Today I went to the sea"

我的代碼是:

if "Today" or "sea" in title: 
     print 1 

if "Today" or "sea" not in title: 
     print 1 

兩個規範導致1

回答

0

更改您的代碼如下:

if "Today" in title or "sea" in title: 
    print 1 

(類似的第二段代碼)。

if陳述的工作原理是他們評估加入詞的表達式,如orand。所以,你的語句讀這樣的:

if ("Today") or ("sea" in title): 
    print 1 

因爲"Today"truthy它一直在評估對true

+2

爲什麼要投票? – winhowes

1

我保證這已經回答了其他地方的SO,你應該先問了一個新問題前檢查有。

與您的代碼的問題:

if 'Today' or 'sea' in title: 

此檢查「今天」是真,或者「海」爲標題,「今天」 ==類型(字符串),因此它的存在/誠然,「海'在標題==真和評估爲真,if 'today' or 'sea' not in title'今天'又是類型(字符串),因此存在/ True和'海'不是在標題=假,並再次評估爲真。如何解決這個問題! if 'Today' in title or 'Sea' in title:或更低版本,使其易於修改!祝你好運!

strings_to_compare = ['Today', 'sea', 'etc...'] 

for i in strings_to_compare: 
    if i in title: 
     print i