Reputation: 64054
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?
Upvotes: 2
Views: 679
Reputation: 90989
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 becomes True
and hence you get ERROR
. What you really want is -
if not (mystr.endswith('.tsv') or mystr.endswith(".csv")):
Or you can use the and
version using De-Morgan's law , which makes not (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 the or
condition). Example -
if not mystr.endswith(('.tsv', ".csv")):
Upvotes: 5