Python 带str.endswith()的条件检查

Python 带str.endswith()的条件检查,python,conditional-expressions,Python,Conditional Expressions,我有以下字符串 mystr = "foo.tsv" 或 在这种情况下,我希望上面的两个字符串总是打印“OK”。 但为什么它失败了呢 if not mystr.endswith('.tsv') or not mystr.endswith(".csv"): print "ERROR" else: print "OK" 正确的方法是什么?它失败了,因为mystr不能同时以.csv和.tsv结束 因此其中一个条件等于False,当您使用not时,它变成True,因此您得到ERROR。

我有以下字符串

mystr = "foo.tsv"

在这种情况下,我希望上面的两个字符串总是打印“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")):
或者您可以使用
版本,使
不是(A或B)
变成
(不是A)和(不是B)


此外,如问题中的注释所述,接受一组后缀进行检查(因此您甚至不需要
条件)。范例-

if not mystr.endswith(('.tsv', ".csv")):
请注意,
endswith()
也接受元组:
如果不是mystr.endswith(('.tsv',.csv)):
if not mystr.endswith(('.tsv', ".csv")):