nev*_*int 2 python conditional-expressions
我有以下字符串
mystr = "foo.tsv"
要么
mystr = "foo.csv"
鉴于这种情况,我希望上面的两个字符串始终打印"OK".但为什么它失败了?
if not mystr.endswith('.tsv') or not mystr.endswith(".csv"):
    print "ERROR"
else:
    print "OK"
什么是正确的方法呢?
这是失败,因为mystr无法与这两个结束.csv,以及.tsv在同一时间.
因此,其中一个条件相当于False,当你使用not它时,它变成了True,因此你得到了ERROR.你真正想要的是 - 
if not (mystr.endswith('.tsv') or mystr.endswith(".csv")):
或者你也可以使用and使用的版本德摩根定律,这使得not (A or B)成(not A) and (not B)
此外,如问题中的注释所述,str.endswith()接受一个后缀元组来检查(因此您甚至不需要or条件).示例 - 
if not mystr.endswith(('.tsv', ".csv")):
| 归档时间: | 
 | 
| 查看次数: | 74 次 | 
| 最近记录: |