If you want the file name to end in ".html" it is perfectly OK to test using if.
You can also use assert, if you want to bubble up an exception to catch it at code a few levels above:
assert url.lower().endswith(".html"), u"the file name must end in .html"
It is just syntactic sugar for:
if url.lower().endswith(".html"):
do_your_things_with_url(url)
else:
raise YourCustomException('the url must end in ".html"')
Of course it would be silly to replace a simple if
test with this:
try:
assert url.lower().endswith(".html")
except AssertionError:
print('Error! url does not end in ".html"')
else:
do_your_things_with_url(url)
So answering your question, you probably should use the if
test for testing if the string ends in ".html".
PS: This style is called LBYL (look before you leap) and there is nothing wrong with it in Python. The alternative is the EAFP (easier to ask for forgiveness than permission). Both are OK and considered idiomatic for most situations with a few exceptions (like for example duck-typing, where the EAFP style is clearly favored against LBYL tests using hasattr
and/or isinstance
). Do not overuse EAFP specially if LBYL is comparatively less expensive - why would you try an expensive operation if a cheap test would work?