社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

jaysunn • 5 年前 • 1314 次点击  

看看这是否是比较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
 
1314 次点击  
文章 [ 1 ]  |  最新文章 5 年前
marcos
Reply   •   1 楼
marcos    5 年前

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

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

if tag not in options:
    ...