2015-10-07 42 views
2

我有以下字符串條件檢查與str.endswith()

mystr = "foo.tsv" 

mystr = "foo.csv" 

鑑於這種情況,我希望上面的兩個字符串始終打印 「OK」。 但它爲什麼會失敗?

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

什麼是正確的做法?

+4

請注意,endswith()也接受一個元組:'if not mystr.endswith(('.tsv',「.csv」)):' – alecxe

回答

5

由於mystr無法同時以.csv以及.tsv結尾,因此它失敗。

所以,其中一個條件相當於False,並且當您使用not時,它變成了True,因此您得到了ERROR。你真正想要的是 -

if not (mystr.endswith('.tsv') or mystr.endswith(".csv")): 

或者你可以使用使用De-Morgan's lawand版本,這使得not (A or B)(not A) and (not B)


而且,在這個問題的評論中指出,str.endswith()接受一個元組的後綴檢查(所以你甚至不需要or條件)。示例 -

if not mystr.endswith(('.tsv', ".csv")):