2016-03-01 114 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