2

我有以下字符串

mystr = "foo.tsv"

或者

mystr = "foo.csv"

鉴于这种情况,我希望上面的两个字符串总是打印“OK”。但为什么会失败?

if not mystr.endswith('.tsv') or not mystr.endswith(".csv"):
    print "ERROR"
else:
    print "OK"

正确的方法是什么?

4

1 回答 1

5

它失败了,因为不能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")):
于 2015-10-07T02:04:56.440 回答