2016-03-01 117 views
0

我目前有兩個,如果在一個字符串查找文本陳述Python的IF和運營商

if "element1" in htmlText: 
    print("Element 1 Is Present") 
    return 

if "element2" in htmlText: 
    print("Element 2 Is Present") 
    return 

這些都工作的偉大,我現在想要做的是增加一個if語句來檢查,如果element3存在,但element1element2都不存在

如何鏈接這3個檢查在一起,是否有像PHP一樣的AND運算符?當比賽之前發現

+0

這樣的事情? [如何針對多個值測試一個變量?](http://stackoverflow.com/q/15112125) –

+2

是的。 'AND'... – skndstry

+0

當然有*和*(這實際上是'和')。但是如果我找到你的想法,你想要「這個條件*和*不是其他條件」? – dhke

回答

4

由於return將返回,它足以把這段代碼:

if "element3" in htmlText: 
    print("Element 3 Is Present") 
    return 
1

嘗試:

if "element1" in htmlText: 
    print("Element 1 Is Present") 
    return 

elif "element2" in htmlText: 
    print("Element 2 Is Present") 
    return 

elif "element3" in htmlText: 
    print("Element 3 Is Present") 
    return 
+0

對於elif,返回語句變得不必要 –

1

Ofcourse在蟒蛇有和運營商。

if "element1" in htmlText and "element2" in htmlText: 
    do something 

或者你仍然可以使用以前的邏輯

if "element1" in htmlText : 
    do...something 
elif "element2" in htmlText : 
    do something 

elif "element3" in htmlText : 
    do something 

else: 
    do other things 
0

無其他答案直接解決這個聲明堅持...

我現在想要做的是增加一個if語句檢查元素3是否存在,但元素1或元素2都不存在

能夠作爲

if "element3" in htmlText and not ("element2" in htmlText or "element1" in htmlText): 
0

提前返回寫入(檢查按照正確的順序條件,請參閱給出答案)通常要明智首選性能。

如果你不能使用早期返回,而是需要對元素的任意條件,請記住你有(列表/詞典)理解。

例如

contains_matrix = [ 
    (element in htmlText) 
    for element in ("element1", "element2", "element3") 
] 

將產生與TrueFalse對於每個元素的列表。 那麼你在問題中提到的條件,可以配製成

not contains_matrix[0] and not contains_matrix[1] and contains_matrix[2] 

讓我再說一遍:相同的結果可以通過檢查"element3"最後和早期恢復來實現。

字典甚至更好(和更Python):

contains_dict = { 
    element: (element in htmlText) 
    for element in ("element1", "element2", "element3") 
} 

評價他們:

(
    not contains_dict['element1'] 
    and not contains_dict['element2'] 
    and contains_dict['element3'] 
) 

甚至

[element for element, contained in contains_dict.items() if contained] 

,讓你所包含的所有元素HTML。

0

我認爲這將是最具可擴展性的解決方案:

elementsToCheck = ['element1','element2','element3'] 
for eIdx, eChk in enumerate(htmlText): 
    if eChk in htmlText: 
     print "Element {0} Is Present".format(eIdx) 
     return 

回答原來的問題(雖然作爲已經指出之前沒有需要它來檢查對其他2個元素):

if 'element3' in htmlText and not ('element1' in htmlText or 'element2' in htmlText): 
    print "Element 3 Is Present" 
    return