Conditional check with str.endswith()

550 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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")):