将变量与多个字符串python3进行比较
看看这是否是比较python3中作为参数传入的字符串变量的最具python风格的方法。我的测试表明这是可行的,但是我不明白为什么将变量与多个字符串python3进行比较,python,python-3.x,Python,Python 3.x,看看这是否是比较python3中作为参数传入的字符串变量的最具python风格的方法。我的测试表明这是可行的,但是我不明白为什么或不起作用,而和会起作用。这只是一个演示,tag变量是从命令行设置的。当我使用centos6、centos7、centos8进行测试时,我点击了else,它按预期工作。这是最好的方法吗?或者这是错误的 tag = 'centos6' if tag != 'centos6' and tag != 'centos7' \ and tag != 'cent
或不起作用,而和会起作用。这只是一个演示,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')
由于或使if
为真如果标记不等于centos
值中的一个值,则无论是其中一个值还是所有值,和仅当if
与所有值不同时才使if
为真。现在写起来更简单:
options=['centos6','centos7','centos8']
标记='centos6'
如果标签不在选项中:
...
也许如果标记不在['centos6'、'centos7'、'centos8']:
或者更好,定义一个名称,比如:允许的操作系统=['centos6'、'centos7'、'centos8']
那么如果标记不在允许的操作系统中:
如果['centos6'、'centos7'、'centos8']中的标记必须是[--os}或[--centos6]或[-]centos7],那么使用打印这个=“好”怎么办[--os centos8]\nfail.format(tag)
然后打印变量