使用str.endswith()进行条件检查

nev*_*int 2 python conditional-expressions

我有以下字符串

mystr = "foo.tsv"
Run Code Online (Sandbox Code Playgroud)

要么

mystr = "foo.csv"
Run Code Online (Sandbox Code Playgroud)

鉴于这种情况,我希望上面的两个字符串始终打印"OK".但为什么它失败了?

if not mystr.endswith('.tsv') or not mystr.endswith(".csv"):
    print "ERROR"
else:
    print "OK"
Run Code Online (Sandbox Code Playgroud)

什么是正确的方法呢?

Ana*_*mar 5

这是失败,因为mystr无法与这两个结束.csv,以及.tsv在同一时间.

因此,其中一个条件相当于False,当你使用not它时,它变成了True,因此你得到了ERROR.你真正想要的是 -

if not (mystr.endswith('.tsv') or mystr.endswith(".csv")):
Run Code Online (Sandbox Code Playgroud)

或者你也可以使用and使用的版本德摩根定律,这使得not (A or B)(not A) and (not B)


此外,如问题中的注释所述,str.endswith()接受一个后缀元组来检查(因此您甚至不需要or条件).示例 -

if not mystr.endswith(('.tsv', ".csv")):
Run Code Online (Sandbox Code Playgroud)