不等于运算符(!=)不能在python字符串比较

时间:2018-02-22 09:39:20

标签: 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

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

2 个答案:

答案 0 :(得分:3)

你的情况:

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':

答案 1 :(得分:0)

您正在if语句中寻找AND条件而不是OR条件。如果你改变了,你应该设置

相关问题