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
mystr
cannot end with both.csv
as well as.tsv
at the same time.So one of the conditions amounts to False, and when you use
not
in that it becomesTrue
and hence you getERROR
. What you really want is -Or you can use the
and
version 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 theor
condition). Example -