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")):