Skip to main content
 首页 » 编程设计

Python 组合条件运算符 : if AA in Y or BB in Y and not B in Y

2025年05月04日33zhujiabin

我想将此代码运行为“if 'Britain' or 'UK' in string do stuff, but don't do stuff if "Ex UK" 在字符串中":

#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。

请您参考如下方法:

在 python 中 the precedence and 高于 or 因此您需要将前 2 个条件放在括号内。

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