Py学习  »  Python

将变量与多字符串python3进行比较

jaysunn • 5 年前 • 1522 次点击  

看看这是否是比较python3中作为参数传入的字符串变量的最python方法。我的测试表明这是有效的,但是我不明白为什么 or 不起作用 and 威尔。这只是一个演示,tag变量是从命令行设置的。当我测试时 centos6, centos7, centos8 我击中了 else 而且工作如期。这是最好的方法吗?还是这错了?

tag = 'centos6'


if tag != 'centos6' and tag != 'centos7' \
        and tag != 'centos8':
    print('[--os %s] must be [--os centos6] or '
          '[--os centos7] or [--os centos8]' % tag)
    print('fail')
else:
    print('good')
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52153
文章 [ 1 ]  |  最新文章 5 年前
marcos
Reply   •   1 楼
marcos    5 年前

因为 or 使 if True 如果 tag 不等于 centos 价值观,不管是一个还是全部, and 使 如果 真的 只有当它不同于所有的值。现在写起来更简单:

options = ['centos6', 'centos7', 'centos8']
tag = 'centos6'

if tag not in options:
    ...