Python组合条件运算符:如果Y中的AA或Y中的BB而不是Y中的B.

时间:2015-07-01 11:48:27

标签: python

我希望将此代码运行为"如果字符串中的'Britain''UK'执行操作,但如果"Ex UK"位于字符串中,则不要执行操作&#34 ;:

#Case insensitive wrapper - equivalent to if X in Y
def case_in(phrase, string):
    return phrase.lower() in string.lower()

name = "Developed Europe Ex UK Property"

#This is the relevant part
if case_in("Britain", name) or case_in(" UK ", name) and not case_in("Ex UK", name):
    geofocusregion = "Europe"
    geofocuscountry = "GB"
    fundcurrency = "GBP"

但是,对于包含"Ex UK"的字符串,它仍设置变量,例如geofocuscountry = GB

3 个答案:

答案 0 :(得分:3)

and的py the precedence高于or所以你需要将前2个条件放在括号内。

if (case_in("Britain", name) or case_in(" UK ", name)) and not case_in("Ex UK", name):

答案 1 :(得分:1)

if(case_in(" Britain",name)或case_in(" UK",name))而不是case_in(" Ex UK",name) :

将前两个条件组合在一起。

答案 2 :(得分:1)

如果你不了解优先顺序

,你应该这样做
-bash: ./Proj: No such file or directory