I have the following string
mystr = "foo.tsv"
or
mystr = "foo.csv"
Given this condition, I expect the two strings above to always print "OK". But why it fails?
if not mystr.endswith('.tsv') or not mystr.endswith(".csv"):
print "ERROR"
else:
print "OK"
What's the right way to do it?
It is failing because
mystrcannot end with both.csvas well as.tsvat the same time.So one of the conditions amounts to False, and when you use
notin that it becomesTrueand hence you getERROR. What you really want is -Or you can use the
andversion using De-Morgan's law , which makesnot (A or B)into(not A) and (not B)Also, as noted in the comments in the question,
str.endswith()accepts a tuple of suffixes to check for (so you do not even need theorcondition). Example -