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

use*_*197 1 python string

我想比较两个strings在python 3.6,如果他们不相等,则打印消息并退出。我当前的代码是:

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
Run Code Online (Sandbox Code Playgroud)

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

lll*_*lll 6

您的情况:

if location.lower() != 'united states of america' or location.lower() != 'usa':
Run Code Online (Sandbox Code Playgroud)

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

我怀疑您想要:

if location.lower() != 'united states of america' and location.lower() != 'usa':
Run Code Online (Sandbox Code Playgroud)

  • 甚至更好:`如果location.lower()不在('美国','美国')中: (2认同)