Skip to main content
 首页 » 编程设计

python之不等于运算符(!=)在 python 字符串比较中不起作用

2025年05月04日24lhb25

我正在尝试比较 python 3.6 中的两个 strings,如果它们不相等,则打印一条消息并退出。我当前的代码是:

location = 'United States of America' 
if location.lower() != 'united states of america' or location.lower() != 'usa': 
    print('Location was different = {}'.format(location.lower())) 
    sys.exit() 
else: 
    #do something 

但是上面的代码无法匹配这两个字符串,即使它们相等,它也会进入循环并打印出它们不同。我知道我犯了一些愚蠢的错误,但无法弄清楚。

请您参考如下方法:

您的情况:

if location.lower() != 'united states of america' or location.lower() != 'usa': 

永远不会是 False,因为 location.lower() 不能同时是 2 个不同的字符串。

我怀疑你想要:

if location.lower() != 'united states of america' and location.lower() != 'usa':